python - 使用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 数据,我可以获得正确的响应。我的代码出了什么问题?
解决方案
而不是数据,你想使用json参数,如下:
datam = {'ayyo' : 'vammo'}
r = requests.get(URL,headers={'Content-Type': 'application/json' }, json=datam)
a = r.json()
# so on
希望有帮助!
推荐阅读
- android - Google PanoramaAPI 停止在 Android 11 上运行
- node.js - 如何将 HTTP 请求重定向到 Windows 上的 localhost?
- shell - Unix Shell:根据其他列值更新列值
- push-notification - 在 ejabberd 20.07 版本中安装和配置 mod_offline_post
- dataframe - 从具有左反连接的另一列中存在的列中删除具有值的行
- java - 在java spring应用程序中加载密钥库时嵌套异常
- azure-ad-b2c - B2C 在 ap.error 内容定义中声明解析器
- swift - SwiftUI 和 Combine - 如何创建一个具有与用户选择对应的字段数的表单
- macos - gdb run 创建一个挂起的线程
- algorithm - 这可能吗?二叉树在 O(root logn) 时间内执行 INSERTION