Python requests模块post请求设置headers不生效返回400错误如何解决
requests.post返回400 Bad Request问题排查
问题复现
你运行的代码及返回结果如下:
>>> import requests >>> api_url = "my_url" >>> headers = {"Content-type": "application/json"} >>> res = requests.post(api_url, "text to post", headers=headers) >>> res.json() {'message': '400: Bad Request', 'code': 0}
错误原因
你在请求头中声明了请求体格式为application/json,但实际传入requests.post的第二个位置参数(即data参数)是普通字符串text to post,该内容不符合JSON格式规范,服务端无法解析请求体,因此返回400错误。
补充说明:即使你要传递纯文本内容作为JSON,合法的JSON字符串也需要用双引号包裹,直接传递无格式的普通字符串会导致请求体非法。
修复方案
- 方案1:使用requests内置
json参数(推荐)
直接传入字典格式的请求数据,requests会自动完成JSON序列化,同时自动添加正确的Content-Type: application/json请求头,无需手动设置:import requests api_url = "my_url" # 按照接口要求构造请求结构,示例为发送content字段存储文本内容 payload = {"content": "text to post"} res = requests.post(api_url, json=payload) print(res.json()) - 方案2:手动序列化JSON后传入data参数
如果你需要手动控制序列化逻辑,可以先将数据序列化为合法JSON字符串后再传递:import requests import json api_url = "my_url" headers = {"Content-type": "application/json"} payload = {"content": "text to post"} res = requests.post(api_url, data=json.dumps(payload), headers=headers) print(res.json()) - 特殊场景:如果接口本身要求接收纯文本格式的请求体,直接修改请求头的Content-Type为对应值即可:
import requests api_url = "my_url" headers = {"Content-type": "text/plain"} res = requests.post(api_url, data="text to post", headers=headers) print(res.json())
内容的提问来源于stack exchange,提问作者AhMeD PS4
相关产品推荐
相关产品推荐

