Python POST二进制数据

Python POST二进制数据,第1张

Python POST二进制数据

基本上您所做的是正确的。查看链接到的redmine文档,URL中的点后的后缀似乎表示发布数据的类型(JSON为.json,XML为.xml),这与您获得的响应-
一致

Processing by AttachmentsController#upload asXML
。我猜可能是文档中存在一个错误,要发布二进制数据,您应该尝试使用
http://redmine/uploads
url而不是
http://redmine/uploads.xml

顺便说一句,我强烈建议在Python中使用非常好的和非常受欢迎的HTTP请求库。它比标准库(urllib2)中的库要好得多。它也支持身份验证,但是为了简洁起见,我跳过了它。

import requestswith open('./x.png', 'rb') as f:    data = f.read()res = requests.post(url='http://httpbin.org/post',         data=data,         headers={'Content-Type': 'application/octet-stream'})# let's check if what we sent is what we intended to send...import jsonimport base64assert base64.b64depre(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data

更新

为了弄清楚为什么它适用于请求而不适用于urllib2,我们必须检查发送内容的差异。要查看此信息,我将流量发送到端口8888上运行的http代理(Fiddler):

使用请求

import requestsdata = 'test data'res = requests.post(url='http://localhost:8888',         data=data,         headers={'Content-Type': 'application/octet-stream'})

我们看

POST http://localhost:8888/ HTTP/1.1Host: localhost:8888Content-Length: 9Content-Type: application/octet-streamAccept-Encoding: gzip, deflate, compressAccept: */*User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vistatest data

并使用urllib2

import urllib2data = 'test data'    req = urllib2.Request('http://localhost:8888', data)req.add_header('Content-Length', '%d' % len(data))req.add_header('Content-Type', 'application/octet-stream')res = urllib2.urlopen(req)

我们得到

POST http://localhost:8888/ HTTP/1.1Accept-Encoding: identityContent-Length: 9Host: localhost:8888Content-Type: application/octet-streamConnection: closeUser-Agent: Python-urllib/2.7test data

我看不出有任何差异可以保证您观察到不同的行为。话虽如此,http服务器检查

User-Agent
标头并根据其值改变行为的情况并不少见。尝试一个接一个地更改请求发送的标头,使其与urllib2发送的标头相同,然后查看何时停止工作。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5616994.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存