如何将原始POST数据传递到urllib3? [英] How do I pass raw POST data into urllib3?

查看:175
本文介绍了如何将原始POST数据传递到urllib3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用urllib3发布JSON编码的数据. 只希望我的POST有效负载为原始JSON字符串,内容类型为application/json. 我只是看不到该怎么做.

Trying to use urllib3 to post JSON-encoded data. Just want my POST payload to be raw JSON string, with content type application/json. I just cannot see how to do this.

urllib3文档描述了字段"中的发布数据,即具有(键,值)对的字典,例如如何用URL对HTML表单进行URL编码.但是我不想那样做.

The urllib3 documentation describes posting data in "fields", i.e. dicts with (key,value) pairs, like how HTML forms are URL-encoded with the URL. But I don't want to do that.

我能得到的最接近的是这个(我只是猜到了数据的存放位置,因为它没有记录在我能找到的任何地方):

The closest I've been able to get is this (I just guessed where to put the data, as it's not documented anywhere that I can find):

http = urllib3.PoolManager()
headers = urllib3.util.make_headers(basic_auth=key+":")
r = http.request_encode_body('POST', path, json.dumps(payload), headers=headers)

这会导致urllib3错误:

which causes this urllib3 error:

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,它会尝试编造身体iself,使用较低级别的urlopen:

you can't use PoolManager.request for that, it tries to concoct the body iself, use the lower level 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"
  }
}

这篇关于如何将原始POST数据传递到urllib3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆