如何将原始POST数据传递到urllib3?

时间:2013-10-07 19:29:42

标签: python post urllib3

尝试使用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)

感谢您的任何指示!

1 个答案:

答案 0 :(得分:5)

你不能使用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"
  }
}
相关问题