如何将数据传递给urllib3 POST-request方法?

2024-10-06 11:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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 })))

问题是在POST请求中以json作为键传递原始json数据。


Tags: importapinodejsonhttppostrequestsv1
1条回答
网友
1楼 · 发布于 2024-10-06 11:30:29

您不需要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'})

相关问题 更多 >