尝试使用 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:Python27libsite-packagesurllib3-1.7.1-py2.7.eggurllib3filepost.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"
}
}