尝试使用 urllib3 发布 JSON 编码数据。
只是希望我的 POST 有效负载是原始 JSON 字符串,内容类型为 application/json。
我只是不知道该怎么做。
urllib3 文档描述了在“字段”中发布数据,即带有(键,值)对的字典,就像 HTML 表单如何使用 URL 进行 URL 编码一样。但我不想那样做。
我能得到的最接近的是这个(我只是猜测将数据放在哪里,因为它没有记录在我能找到的任何地方):
http = urllib3.PoolManager()
headers = urllib3.util.make_headers(basic_auth=key+":")
r = http.request_encode_body('POST', path, json.dumps(payload), headers=headers)
这会导致 urllib3 错误:
File "C:\Python27\lib\site-packages\urllib3-1.7.1-py2.7.egg\urllib3\filepost.py", line 44, in iter_field_objects
yield RequestField.from_tuples(*field)
TypeError: from_tuples() takes exactly 3 arguments (2 given)
感谢您的指点!
你不能使用PoolManager.request
为此,它尝试自己构建身体,使用较低的水平urlopen
:
In [16]: pool = urllib3.PoolManager()
In [17]: print pool.urlopen('POST', 'http://httpbin.org/post', headers={'Content-Type':'application/json'}, body='{"sup":"son"}').data
{
"data": "{\"sup\":\"son\"}",
"form": {},
"json": {
"sup": "son"
},
"origin": "50.74.23.243",
"args": {},
"url": "http://httpbin.org/post",
"files": {},
"headers": {
"Host": "httpbin.org",
"Content-Length": "13",
"Content-Type": "application/json",
"Accept-Encoding": "identity",
"Connection": "close"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)