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

Python Requests无法设置application/x-www-form-urlencoded请求头问题

问题分析与解决

首先要明确:你打印的dorefresh.headers是服务器返回的响应头,不是你发送给服务器的请求头。服务器返回Content-Type: application/json,仅代表它用JSON格式返回数据,和你发送的请求头没有关联。

查看实际发送的请求头

要确认自己的请求头是否正确,需要打印请求对象的headers,而非响应的headers。在代码中添加这段即可:

print("发送的请求头:")
for header, value in dorefresh.request.headers.items():
    print(f'{header}: {value}')

requests的默认请求头规则

当你用data参数传递字典时,requests会自动将数据编码为application/x-www-form-urlencoded格式,同时自动设置对应的请求头。你手动在headers里指定Content-Type其实是多余操作,但不会引发问题。

若请求头被意外篡改的处理方案

如果你的运行环境(如代理、框架拦截)导致请求头被篡改,可以手动将字典转为URL编码字符串后再发送:

import urllib.parse

data2 = {"grant_type": "refresh_token", "refresh_token": config_keys['cc_api_refresh'],"client_id": config_keys['client_id']}
# 将字典编码为x-www-form-urlencoded格式的字符串
encoded_data = urllib.parse.urlencode(data2)
dorefresh = requests.post(
    config_urls['cc_refresh_url'],
    data=encoded_data,
    headers={"Content-Type": "application/x-www-form-urlencoded"}
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 04:11:07