python - 将 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.'}
解决方案
根据文档:
除了自己编码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)
推荐阅读
- ruby-on-rails - 具有 1 对 1 关联的 Rails STi
- r - 将变量重新编码为 R 中带有级别名称的因子
- vue.js - 当 Vue-Cli 项目通过 tomcat 服务时服务器返回 404
- c# - 编码 API 可以解码流/非连续字节吗?
- javascript - 在javascript中使用Name而不是Id获取输入类型文本的值
- swift - Swift - 动画 ImageView
- ios - point 和 hitTest 有什么区别以及如何使用 hitTest?
- python - 根据另一个列条件将列表替换为数据框中的另一个列表
- python - 当我的函数 A 只需要在 B 中运行时,如何将它作为函数 B 的参数?(Python)
- android - 为什么我的应用程序的某些部分在一个上下文中工作而在另一个上下文中不工作?