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

如何让Python发送请求时不在请求头中添加单引号?

解决Python requests发送Authorization请求头的问题

首先澄清一个关键误解:你看到的'Authorization': 'api_key'只是Python字典的字符串输出格式,不是实际发送给服务器的HTTP请求头内容。requests库在发送请求时,会自动将字典格式的headers转换为标准的HTTP请求头格式,和curl发送的Authorization: api_key完全一致,不会添加单引号。

服务器返回500错误的原因大概率不是请求头的单引号问题,而是以下几种常见情况:

  • API要求Authorization头带特定前缀:很多API要求认证头包含前缀,比如Bearer 或ApiKey ,而非直接传递api_key。例如:

    # 示例:带Bearer前缀
    headers = {"Authorization": "Bearer your_real_api_key"}
    res = requests.post("https://endpoint.com/Login/authenticate", headers=headers)
    
  • api_key本身包含特殊字符:如果你的api_key里有单引号、空格或其他特殊字符,可能导致服务器解析失败。可以尝试对api_key进行URL编码后再传递:

    import urllib.parse
    encoded_key = urllib.parse.quote_plus("your_api_key_with_special_chars")
    headers = {"Authorization": encoded_key}
    res = requests.post("https://endpoint.com/Login/authenticate", headers=headers)
    
  • api_key无效或格式错误:检查api_key是否拼写正确、大小写是否匹配,或者是否已过期/权限不足。

验证实际发送的请求头

可以通过开启requests的调试日志,查看实际发送的HTTP请求头内容,确认格式正确:

import requests
import logging

# 开启调试日志,查看请求详情
logging.basicConfig(level=logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

headers = {"Authorization": "your_api_key"}
res = requests.post("https://endpoint.com/Login/authenticate", headers=headers)

运行后,日志中会显示实际发送的请求头,你会看到它和curl的格式完全一致,没有单引号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:05:31