如何使用urllib3在Python上发出Post请求?

时间:2022-01-05 11:20:21

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的第一天如果我说得不够具体的话,请见谅。

1 个解决方案

#1


6  

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?

#1


6  

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?