如何使用urllib3在Python上发布帖子请求?

use*_*742 4 python json curl urllib3

我一直在尝试向API发出请求,我必须通过以下正文:

{
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
}
Run Code Online (Sandbox Code Playgroud)

尽管代码似乎是正确的,并且它以"处理完成退出代码0"结束,但它运行不正常.我不知道我错过了什么,但这是我的代码:

http = urllib3.PoolManager()
http.urlopen('POST', 'http://localhost:8080/assets', headers={'Content-Type':'application/json'},
                 data={
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
})
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这是使用Python的第一天,如果我不够具体,请原谅我.

sha*_*zow 11

由于您尝试传入JSON请求,因此您需要将主体编码为JSON并将其传入body字段.

对于您的示例,您想要执行以下操作:

import json
encoded_body = json.dumps({
        "description": "Tenaris",
        "ticker": "TS.BA",
        "industry": "Metalúrgica",
        "currency": "ARS",
    })

http = urllib3.PoolManager()

r = http.request('POST', 'http://localhost:8080/assets',
                 headers={'Content-Type': 'application/json'},
                 body=encoded_body)

print r.read() # Do something with the response?
Run Code Online (Sandbox Code Playgroud)

编辑:我原来的答案是错的.更新它以编码JSON.另外,相关问题:如何将原始POST数据传递到urllib3?