Python Requests 错误:无效的请求头名称 - ':authority'
Python Requests 库在发送 HTTP 请求时,可能会遇到 'requests.exceptions.InvalidHeader: Invalid leading whitespace, reserved character(s), or returncharacter(s) in header name: ':authority'' 错误。
这个错误表示您尝试设置的请求头名称包含无效字符,例如:
- 前导空格: 请求头名称不能以空格开头。
- 保留字符: 请求头名称不能包含以下保留字符:
- 空格
- 冒号 (:)
- 逗号 (,)
- 反斜杠 ()
- 双引号 (')
- 尖括号 (<, >)
- 方括号 ([, ])
- 花括号 ({, })
- 等号 (=)
- 问号 (?)
- &
- #
- 返回字符: 请求头名称不能包含回车符或换行符。
解决方法:
- 检查您的代码: 确保您设置的请求头名称没有包含任何无效字符。
- 使用正确的请求头名称: 例如,要设置 'Host' 请求头,应使用 'Host' 而不是 ':authority'。
- 避免手动设置请求头: 如果可能,尽量使用 Requests 库提供的内置方法来设置请求头,例如 'headers' 参数。
示例:
import requests
url = 'https://www.example.com'
# 错误:包含无效字符的请求头
headers = {'':authority': 'www.example.com'}
response = requests.get(url, headers=headers)
# 正确:使用正确的请求头名称
headers = {'Host': 'www.example.com'}
response = requests.get(url, headers=headers)
原文地址: https://www.cveoy.top/t/topic/nBiD 著作权归作者所有。请勿转载和采集!