Bla*_*der 2 python urllib3 python-2.7 python-requests
我想使用urllib3
库来通过库发出 POST 请求,requests
因为它具有连接池和重试等功能。但我找不到以下POST
请求的替代品。
import requests
result = requests.post("http://myhost:8000/api/v1/edges", json={'node_id1':"VLTTKeV-ixhcGgq53", 'node_id2':"VLTTKeV-ixhcGgq51", 'type': 1 })
Run Code Online (Sandbox Code Playgroud)
这在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 })))
Run Code Online (Sandbox Code Playgroud)
问题是json
在POST
请求中使用as 键传递原始 json 数据。
您不需要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'})
Run Code Online (Sandbox Code Playgroud)