【问题标题】:Do we need to do json.dumps and encode before making a Python POST request?在发出 Python POST 请求之前,我们是否需要进行 json.dumps 和编码?
【发布时间】:2019-10-01 09:54:46
【问题描述】:

问题 1) 在发出 Python POST 请求之前,我们是否需要进行 json.dumps 和编码?

通常请求是:

response = requests.post('https://httpbin.org/post', json={'key':'value'})

问题 2)

是否建议这样做?:

x1 = {'key':'value'}
x2 = json.dumps(x1)
x3 = x2.encode()
response = requests.post('https://httpbin.org/post', json=x3)

问题 3) 在发出 Python POST 请求之前,我们什么时候需要做 json.dumps 和编码?

【问题讨论】:

  • 您可以在response = requests.post('https://httpbin.org/post', data={'key':"value"}) 中将数据作为data 参数传入您还可以在标题参数中将适当的内容类型设置为字典

标签: python json python-3.x python-requests


【解决方案1】:

不,如果你使用json 参数,它应该是一个字典。来自the documentation

json –(可选)一个 JSON 可序列化 Python 对象,用于在请求正文中发送。

【讨论】:

    【解决方案2】:

    您只需要在发出下面给出的发布请求之前使用转储您的数据-

    url = "http://localhost:8080"
    obj = {'City': 'Delhi', 'Country': 'India', 'message': 'Hello Team!'}
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    requests.post(url, data=json.dumps(obj), headers=headers)
    

    注意:我在测试期间观察到的 转储 在 POST 请求中是不必要的。它也应该只适用于data=obj

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      相关资源
      最近更新 更多