首页 > 解决方案 > 将 dict 和 json 都传递给 url

问题描述

我必须在查询中使用需要 JSON 和非 json 的 web 服务端点,而且我不知道如何使用 requests 包来做到这一点。提供的相同代码中包含 http.client,由于不相关的原因,我无权访问该项目中的该包

示例代码是:

import http.client

conn=http.client.HTTPSConnection('some.url')
payload="{\"some_json_dict_key\": \"some_json_dict_value\"}"
headers={'content-type': "application/json", 'accept': "application/json"}
conn.request("POST", "/someEndpoint?param1=value_of_param1", payload, headers)
res = conn.getresponse()
data = res.read().decode('utf-8')

我尝试过的代码不起作用:

import requests

headers={'content-type': "application/json", 'accept': "application/json"}
params={'param1': 'value_of_param1'}
json_payload = "{\"some_json_dict_key\": \"some_json_dict_value\"}"
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)

但是这似乎不起作用我得到了例外

{'httpMessage': 'Bad Request', 'moreInformation': 'The body of the request, which was expected to be JSON, was invalid, and could not be decoded. The start of an object { or an array [ was expected.'}

标签: pythonjsonpython-requests

解决方案


根据文档

除了自己编码dict,你也可以直接使用json参数(在2.4.2版本中添加)传递它,它将自动编码:

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, json=payload)

但是您将字符串传递给json参数(我承认错误消息可能更清楚)。所有其他参数都是 json/dict 对象。制作json_payload一本真正的字典。

json_payload = {"some_json_dict_key": "some_json_dict_value"}  # real dictionary, not a json string
url = 'https://some.url/someEndpoint'
response = requests.post(url, headers=headers, data=params, json=json_payload)

推荐阅读