繁体   English   中英

使用python请求库在HTTP请求中发送json

[英]Using python requests library to send json in http request

我正在尝试使用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}

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

您要使用json参数代替数据,如下所示:

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

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM