如何编写python脚本以使用http与远程服务交互

2024-06-10 17:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本,用http与远程web服务器进行交互。这是服务器(名称:username;密码:passw0rd),基本上我需要上传一个图像到远程服务器,并打印出它的分析输出。你知道吗

我对Python网络编程几乎一无所知,真的不知道如何解决这个问题。有人能告诉我从哪里开始写这样的剧本吗?我可以从chrome找到以下http post请求,但不知道如何继续:

POST /post HTTP/1.1
Host: 34.65.71.65
Connection: keep-alive
Content-Length: 3185
Cache-Control: max-age=0
Authorization: Basic dXNlcm5hbWU6cGFzc3cwcmQ=
Origin: http://34.65.71.65
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryUPXn3eOKoasOQMwW
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Referer: http://34.65.71.65/post
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7

这是我现在正在写的Python脚本:


import requests

# defining the api-endpoint
API_ENDPOINT = "http://34.65.71.65/post"

# your API key here
username = "username"
pwd = "passw0rd"

path = "./kite.png"
image_path = path
# Read the image into a byte array
image_data = open(image_path, "rb").read()

# data to be sent to api
data = image_data

# sending post request and saving response as response object
# r = requests.post(url = API_ENDPOINT, auth=(username, pwd), data = data)
r = requests.post(url = API_ENDPOINT, auth=(username, pwd), data = data)

# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

但不知何故,它引发了以下问题:


requests.exceptions.ConnectionError: ('Connection aborted.', BrokenPipeError(32, 'Broken pipe'))

这是另一个试验:

import requests

# defining the api-endpoint
API_ENDPOINT = "http://34.65.71.65/post"

# your API key here
username = "username"
pwd = "passw0rd"

path = "./kite.png"

with open(path, 'rb') as file:
    body = {'foo': 'bar'}
    body_file = {'file_field': file}
    response = requests.post(API_ENDPOINT, auth=(username, pwd), data=body, files=body_file)
    print(response.content) # Prints result


Tags: pathimageapihttpurldataresponsepwd
0条回答
网友
1楼 · 发布于 2024-06-10 17:14:50

借助requests API,用Python发出HTTP请求非常容易。上传一个文件需要你先读取它,然后上传到POST请求的主体中。你知道吗

当服务器在客户端发送所有数据之前关闭连接时,经常会发生断管错误。这通常是由于标题中声明的内容大小与实际内容大小不一致造成的。要解决此问题,您应该将文件读取为“r”或“rb”(如果是二进制文件),并使用requests API files kwargs发送文件。你知道吗

import requests

with open(file.name, 'rb') as file:
      body = {'foo': 'bar'}
      body_file = {'file_field': file}
      response = requests.post('your.url.example', data=body, files=body_file)
      print(response.content) # Prints result

相关问题 更多 >