在Python中发送HTTP2请求时收到重复的伪头字段 b':path' 错误

0 投票
2 回答
39 浏览
提问于 2025-04-13 18:43

我有一个网址,它只接受http2请求。

当我想用Python向这个网址发送http/2请求时,出现了下面的错误

h2.exceptions.ProtocolError: 收到了重复的伪头字段 b':path'

我的代码

from hyper.contrib import HTTP20Adapter
import requests
MyHeader={
    
  "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"
    }

adapter = HTTP20Adapter(headers=MyHeader)
sessions=requests.session()
sessions.mount(prefix='https://myurl.com', adapter=adapter)
r=sessions.get('Continue_My_Url_response')
print(r)

我之前一直用requests库来处理HTTP/1,这是我第一次想用HTTP/2

有没有人能给我一些建议或者例子,教我怎么通过HTTP/2发送这个请求?

2 个回答

0

感谢 @jerion5562:

我使用了下面的代码,成功了:

首先:安装这个库 pip install httpx[http2]

import httpx
client = httpx.Client(http2=True)
response =  client.get(My_Url,headers=MyHeader)
print(response.http_version) # HTTP/2
print(response.status_code) # 200 
0

使用httpx并开启http/2支持的方法是:httpx.Client(http2=True)

撰写回答