将dict和json都传递到网址

时间:2019-06-26 19:22:02

标签: python json python-requests

我必须使用在查询中同时需要JSON和非JSON的Web服务端点,而且我不知道如何使用请求包进行操作。所提供的相同代码中包含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.'}

2 个答案:

答案 0 :(得分:1)

根据documentation

  

除了自己对dict进行编码外,您还可以使用json参数(在2.4.2版中添加)直接传递dict,它将自动进行编码:

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

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

但您要将 string 传递到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)

答案 1 :(得分:0)

您必须意识到POST请求可以在两个地方传递信息:在请求的正文(数据)中以及URL字符串中(请求参数与GET请求一样)。在示例中,您没有完全模拟,参数在URL字符串中,根据收到的错误消息,正文必须由单个JSON对象组成。因此,使用params字典作为URL参数,如下所示:

response = requests.post(url, headers=headers, params=params, data=json_payload)

应该这样做,除非还有其他细节需要处理。