如何向urllib3 POST请求方法传递数据?

问题描述 投票:0回答:1

我想使用

urllib3
库通过
requests
库发出 POST 请求,因为它具有连接池和重试等功能。但我不能 找到以下
POST
请求的任何替代品。

import requests
result = requests.post("http://myhost:8000/api/v1/edges", json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })

这与

requests
库运行良好,但我无法将其转换为
urllib3
请求。 我试过了

import json
import urllib3
urllib3.PoolManager().request("POST","http://myhost:8000/api/v1/edges", body=json.dumps(dict(json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })))

问题是在

json
请求中传递以
POST
作为关键的原始 json 数据。

python python-2.7 python-requests urllib3
1个回答
11
投票

您不需要

json
关键字参数;你正在将你的字典包装在另一本字典中。

您还需要添加一个

Content-Type
标题,将其设置为
application/json
:

http = urllib3.PoolManager()
data = {'node_id1': "VLTTKeV-ixhcGgq53", 'node_id2': "VLTTKeV-ixhcGgq51", 'type': 1})
r = http.request(
    "POST", "http://myhost:8000/api/v1/edges", 
    body=json.dumps(data),
    headers={'Content-Type': 'application/json'})
© www.soinside.com 2019 - 2024. All rights reserved.