在 python 3 中询问 HTTP/2 切换协议

Asking for HTTP/2 Stwitching Protocols in python 3

我正在尝试使用 python 3 脚本检查 http 服务是否支持 HTTP/2。 不幸的是,在我的脚本上花费了大量研究和大量时间之后,我没有执行它。

这是我的:

import sys
import http.client as HttpClient

h2c = {
  "User-agent": 'python/' + str(sys.version.split()[0]),
  "Connection": "Upgrade, HTTP2-Settings",
  "Upgrade": "h2c",
  "HTTP2-Settings": "AAMAAABkAAQAAP__",
  "Accept": "*/*"
}

c = HttpClient.HTTPSConnection(ip, port) # IP and port given in arguments
c.request('HEAD', '/', None, h2c)
r = c.getresponse()
# Print result (see below)

我知道它存在 hyper 但我并不总是想要 SSL,目前无法使用 hyper

禁用证书验证

这是我在本地主机上的脚本 运行 的示例:

➜  http2 git:(master) ✗ python3 main.py -i localhost -p 443

HEAD / HTTP/1.1
Host: localhost
Upgrade: h2c
User-agent: python/3.4.2
Accept: */*
Connection: Upgrade, HTTP2-Settings
HTTP2-Settings: AAMAAABkAAQAAP__

HTTP/1.1 200 OK
Server: nginx/1.9.12
Date: Tue, 22 Mar 2016 15:05:15 GMT
Content-Type: text/html
Content-Length: 867
Last-Modified: Mon, 21 Mar 2016 10:03:18 GMT
Connection: keep-alive
ETag: "56efc6e6-363"
Accept-Ranges: bytes

我检查过 HTTP/2 在我的 nginx 服务器上启用(curl --http2

如果有人有想法强制服务器回复 HTTP 101 ...

HTTP/2 可以通过两种方式协商:通过 ALPN 的 TLS 或通过明文 HTTP/1.1 升级。

您在这里所做的是两种方法的混合:您正在使用 TLS 连接并发送 HTTP/1.1 升级。

您应该改为使用 TLS 连接,使用客户端支持的协议列表指定 ALPN 扩展(在您的情况下,至少 h2),然后 - 如果服务器接受说 HTTP/2 - 开始直接发送 HTTP/2 帧(不是 HTTP/1.1 升级)。

我不是 Python 专家,但可以指定 ALPN 协议,请参阅 and here

您还想查看实施 HTTP/2 的 other Python projects