我必须使用一个在查询中同时需要 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.'}
最佳答案
根据documentation :
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
>>> 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)
关于python - 将 dict 和 json 传递给 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56779745/