You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用requests库发送POST请求返回400错误如何排查解决?

是的,该400错误完全有可能由请求头语法或格式错误导致,结合你提供的代码,可定位到以下几个明确的错误点:

  • 手动写死了错误的Content-Length请求头:你传入的请求体是空JSON对象{},序列化后的实际长度远小于你填写的1847。requests库会自动根据请求体内容计算正确的Content-Length,手动写死错误值会导致服务器等待接收剩余的请求内容,最终判定请求格式非法返回400。
  • 请求头中存在HTML转义字符:Sec-Ch-Ua和Sec-Ch-Ua-Platform字段中的"是HTML格式的转义双引号,直接放在请求头中属于语法错误,需要替换为普通双引号"。
  • Accept请求头格式错误:你代码中Accept的值为application/json, text/plain, /,最后一个值缺少通配符*,正确写法应为*/*。

修复后的代码示例

import requests

headers = {
    'Host': 'host.url',
    'Sec-Ch-Ua': '"Chromium";v="95", ";Not A Brand";v="99"',
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    'Authorization': 'auth-key',
    'Sec-Ch-Ua-Mobile': '?0',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Origin': 'origin.url',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'referer.url',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
    'Connection': 'close',
}

data = {}
# 直接使用json参数传递字典,requests会自动完成序列化、设置对应请求头
response = requests.post('替换为实际请求地址', json=data, headers=headers, verify=False)
print(response.text)

内容的提问来源于stack exchange,提问作者harish bharadwaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:54:08