如何使用 urllib3 在 Python 上发出 Post 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31778800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a Post Request on Python with urllib3?
提问by user1953742
I've been trying to make a request to an API, I have to pass the following body:
我一直在尝试向 API 发出请求,我必须传递以下正文:
{
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
}
Altough the code seems to be right and it finished with "Process finished with exit code 0", it's not working well. I have no idea of what I'm missing but this is my code:
尽管代码似乎是正确的,并且它以“进程已完成,退出代码为 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"
})
By the way, this the first day working with Python so excuse me if I'm not specific enough.
顺便说一句,这是使用 Python 的第一天,所以如果我不够具体,请见谅。
回答by shazow
Since you're trying to pass in a JSON request, you'll need to encode the body as JSON and pass it in with the body
field.
由于您尝试传入 JSON 请求,因此您需要将主体编码为 JSON 并将其与body
字段一起传入。
For your example, you want to do something like:
对于您的示例,您想要执行以下操作:
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?
Edit: My original answer was wrong. Updated it to encode the JSON. Also, related question: How do I pass raw POST data into urllib3?
编辑:我原来的答案是错误的。更新它以对 JSON 进行编码。另外,相关问题:如何将原始 POST 数据传递到 urllib3?