将多部分映像发布到api

2024-05-16 03:09:58 发布

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

邮递员投递:

请求有效载荷:

------WebKitFormBoundaryiPTu5XrX314NHpan
Content-Disposition: form-data; name="photo"; filename="example1.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryiPTu5XrX314NHpan--

在标题中:

^{pr2}$

需要从python应用程序发送图像,但每次都会收到400个错误。在

尝试:

req = urllib2.Request(photoURL, None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
imgFile = cStringIO.StringIO(urllib2.urlopen(req).read())
datagen, headers = multipart_encode({"photo": Image.open(imgFile)})
request = urllib2.Request(postPhotoAPI, datagen, headers)
request.add_header("Authorization", authKey)
urllib2.urlopen(request).read()

结果:400

相同的请求.post以及其他一些post函数(也适用于base64)。在


Tags: 邮递员readrequestwindowscontenturllib2postreq
1条回答
网友
1楼 · 发布于 2024-05-16 03:09:58

当我想用python进行http调用时,我总是使用pythonrequests库。在

你需要这样做:

files = {'photo': ('image.png', open('image.png', 'rb'), 'image/png')}
r = requests.post(photoURL, header={'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5', 'Authorization': authKey} files=files)
print r.text

您可以阅读更多here。在

相关问题 更多 >