【问题标题】:How to pass data to urllib3 POST request method?如何将数据传递给 urllib3 POST 请求方法?
【发布时间】:2015-11-24 14:28:28
【问题描述】:

我想使用 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 数据。

【问题讨论】:

    标签: python python-2.7 python-requests urllib3


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2020-05-17
      相关资源
      最近更新 更多