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

使用Python发送HTTP/2请求时遭遇重复伪头字段错误求助

解决HTTP/2请求中重复伪头字段的错误

错误原因

h2.exceptions.ProtocolError: Received duplicate pseudo-header field b':path' 错误是由于HTTP/2请求中重复发送了:path伪头字段导致的。你的代码里,HTTP20Adapter初始化时传入的headers参数与requests内部的HTTP/2请求处理逻辑冲突,触发了伪头重复添加的问题。

解决思路及修正代码

方案1:调整请求头传递方式

不要在HTTP20Adapter初始化时传入自定义头,改为在get请求中通过headers参数传递,避免与adapter的伪头生成逻辑冲突:

from hyper.contrib import HTTP20Adapter
import requests

# 定义自定义请求头
my_headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"
}

session = requests.session()
# 初始化adapter时不传入headers参数
adapter = HTTP20Adapter()
session.mount('https://myurl.com', adapter)

# 使用完整URL或正确相对路径发起请求,同时传递自定义头
response = session.get('https://myurl.com/Continue_My_Url_response', headers=my_headers)
print(response.status_code)
print(response.text)

方案2:使用原生支持HTTP/2的httpx库

requests本身不原生支持HTTP/2,依赖第三方adapter易出现兼容性问题。httpx库原生支持HTTP/2,用法更简洁:

import httpx

my_headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"
}

# 启用HTTP/2的客户端
with httpx.Client(http2=True) as client:
    response = client.get('https://myurl.com/Continue_My_Url_response', headers=my_headers)
    print(response.status_code)
    print(response.text)

注意事项

  • 确保请求URL格式正确:使用完整URL或带斜杠的相对路径(如/Continue_My_Url_response),避免路径拼接错误引发伪头异常。
  • 检查依赖版本:如果坚持使用requests+HTTP20Adapter,请确保hyper库为最新版本,规避已知的协议处理bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 11:43:36