我正在尝试向服务器(虚拟托管)发出 HTTP2 请求,该服务器根据主机标头值(SNI)提供 SSL 证书。
# conn = hyper.HTTP20Connection('http2.akamai.com', port=443, ssl_context=context)
# conn.request('GET', '/path', headers={'Host': 'www.mywebsite.com'})
Python 的 Hyper-h2 包不支持 SNI 或禁用证书验证! https://hyper.readthedocs.io/en/latest/advanced.html#ssl-tls-certificate-verification
禁用证书验证的一种方法是使用自定义 SSLContext,并陷入协议断言错误
使用自定义 SSLContext 进行 HTTP2 调用的基本代码:
import ssl
import hyper
# Custom SSLCONTEXT for not verifying SSLCertificate and Hostname
# or need SSLCONTEXT for SNI support
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
context.check_hostname = False
hyper.tls._context = context
conn = hyper.HTTP20Connection('http2.akamai.com', port=443, ssl_context=context)
conn.request('GET', '/')
print conn.get_response()
错误 :
Traceback (most recent call last):
File "ssl_custom.py", line 32, in <module>
conn.request('GET', '/')
File "/usr/local/lib/python2.7/site-packages/hyper/http20/connection.py", line 281, in request
self.endheaders(message_body=body, final=True, stream_id=stream_id)
File "/usr/local/lib/python2.7/site-packages/hyper/http20/connection.py", line 544, in endheaders
self.connect()
File "/usr/local/lib/python2.7/site-packages/hyper/http20/connection.py", line 373, in connect
assert proto in H2_NPN_PROTOCOLS or proto == H2C_PROTOCOL
AssertionError
编辑/更新:现在我学会了如何正确构建上下文init_context()
,当向启用 SNI 的服务器发出请求时,问题仍然存在。
ssl_context = init_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_OPTIONAL
headers={'Host': 'www.opentable.com'}
conn = hyper.HTTP20Connection('ev-www.opentable.com.edgekey.net', port=443, ssl_context=ssl_context)
conn.request('GET', '/washington-dc-restaurants', headers=headers)
print conn.get_response()
输出:
assert proto in H2_NPN_PROTOCOLS or proto == H2C_PROTOCOL
需要一种方法来在 Hyper 中指定 SNI 或 Curl 等效 --resolve 功能