python - 将 dict 和 json 传递给 url

标签 python json python-requests

我必须使用一个在查询中同时需要 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/

相关文章:

python - 如何捕获上下文中未定义名称的异常?

python - Django 表单在创建用户时不保存密码

python - GridSearchCV 和 Google colab : n_jobs=-1 does not work

c# - 在默认构造函数中初始化的 JSON.Net 集合未被反序列化的 JSON 覆盖

mySQL 5.7 使用新的 json 功能将行作为 json 返回

Python请求未获取所有数据

python - 如何使用 pathos 避免过多的内存消耗

python - 推特情绪分析技术

java - 对象列表的 JSON 结构

python - 无法使用 python Minds api 进行身份验证