首页 > 解决方案 > 使用python请求库在http请求中发送json

问题描述

我正在尝试使用 python 请求库发送一个 http GET 请求。以下是我的代码。

#!/usr/bin/python3
import requests
import json

URL = some-elkstack-url

datam = {'ayyo' : 'vammo'}
data_json = json.dumps(datam)
payload = {'json_payload': data_json}
header={'Content-Type': 'application/json' }
r = requests.get(url=URL, headers=header, data=datam)
a = r.json()
print('\nResponse: \n')
print(a)

我从服务器收到了这个 HTTP 错误。

{'error': {'root_cause': [{'type': 'json_parse_exception', 'reason': "Unrecognized token 'ayyo': was expecting ('true', 'false' or 'null')\n at 
[Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@74cef381; line: 1, column: 6]"}], 'type': 'json_parse_exception', 'reason': "Unrecognized token 'ayyo': was expecting ('true', 'false' or 'null')\n at 
[Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@74cef381; line: 1, column: 6]"}, 'status': 500}

当我从命令行执行 curl 时,使用相同的 json 数据,我可以获得正确的响应。我的代码出了什么问题?

标签: pythonjsonhttppython-requests

解决方案


而不是数据,你想使用json参数,如下:

datam = {'ayyo' : 'vammo'}
r = requests.get(URL,headers={'Content-Type': 'application/json' }, json=datam)
a = r.json()
# so on

希望有帮助!


推荐阅读