如何使用urllib3在Python上发出发布请求? [英] How can I make a Post Request on Python with urllib3?

查看:106
本文介绍了如何使用urllib3在Python上发出发布请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to make a request to an API, I have to pass the following body:

{
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
}

虽然代码似乎是正确的,但它以处理结束,退出代码为0结束,效果不佳。我不知道自己缺少什么,但这是我的代码:

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:

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"
})

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

By the way, this the first day working with Python so excuse me if I'm not specific enough.

推荐答案

由于您尝试传递JSON请求,因此需要将主体编码为JSON并传递在 body 字段中输入。

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.

例如,您想要执行以下操作:

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?

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

这篇关于如何使用urllib3在Python上发出发布请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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