
本文介绍如何在 Python 中正确发送 HTTP/2 请求,解决因重复 :path 伪头字段导致的 ProtocolError,推荐使用现代、原生支持 HTTP/2 的 httpx 库替代已不维护的 hyper + requests 组合。
本文介绍如何在 python 中正确发送 http/2 请求,解决因重复 `:path` 伪头字段导致的 `protocolerror`,推荐使用现代、原生支持 http/2 的 `httpx` 库替代已不维护的 `hyper` + `requests` 组合。
在 Python 中实现 HTTP/2 请求时,许多开发者会尝试沿用熟悉的 requests 库配合 hyper.contrib.HTTP20Adapter,但该方案存在严重兼容性问题:HTTP20Adapter 已长期未维护(最后更新于 2018 年),且与 requests 的底层请求构造逻辑冲突——它会在已由 requests 自动注入 :path、:method、:scheme、:authority 等 HTTP/2 必需伪头字段的前提下,再次手动添加 :path,从而触发 h2.exceptions.ProtocolError: Received duplicate pseudo-header field b':path' 错误。
✅ 正确做法是切换至原生、活跃维护、符合 HTTP/2 规范的客户端:httpx。它由 requests 原作者团队主导开发,全面支持异步/同步、HTTP/1.1 和 HTTP/2,并自动处理伪头字段的生成与校验,杜绝重复问题。
✅ 推荐实现(同步方式)
import httpx
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, headers=headers) as client:
response = client.get("https://myurl.com/Continue_My_Url_response")
print(f"Status: {response.status_code}")
print(f"HTTP Version: {response.http_version}") # 输出 'HTTP/2' 表示成功
⚠️ 注意事项
- 安装依赖:pip install httpx[http2]([http2] 额外依赖会自动安装 h2 和 certifi);
- httpx.Client(http2=True) 会自动协商 ALPN 协议,若目标服务器不支持 HTTP/2,则优雅降级为 HTTP/1.1(可通过 response.http_version 验证);
- 不要手动设置 :path、:method 等伪头字段——httpx 会根据 URL 和请求方法自动生成,强行添加将引发协议错误;
- 若需复用连接或自定义 SSL 上下文,可传入 http2=True 同时配置 limits 或 verify 参数,无需额外适配器。
? 扩展建议
对于高并发场景,推荐使用异步版本以获得更高吞吐:
import httpx
import asyncio
async def fetch():
async with httpx.AsyncClient(http2=True, headers=headers) as client:
r = await client.get("https://myurl.com/Continue_My_Url_response")
return r
# 运行:asyncio.run(fetch())
综上,放弃过时的 hyper + requests 组合,拥抱 httpx 是解决 HTTP/2 伪头冲突、提升稳定性和可维护性的最佳实践。










