【问题标题】:Perform handshake only once只执行一次握手
【发布时间】:2016-05-02 06:00:55
【问题描述】:
我使用urllib.request.urlopen 通过HTTPS 从服务器获取数据。该函数被多次调用到同一个服务器,通常是完全相同的 url。但是,与在初始请求时执行握手的标准 Web 浏览器不同,调用单独的 urlopen(url) 将导致每次调用都进行新的握手。这在高延迟网络上非常很慢。有没有办法执行一次握手并重用现有连接以进行进一步的通信?
我无法修改服务器代码以使用套接字或其他协议。
【问题讨论】:
标签:
python-3.x
https
handshake
urlopen
【解决方案1】:
您正在为每个请求打开一个新连接。要重用连接,您需要使用http.client:
>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read() # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while not r1.closed:
... print(r1.read(200)) # 200 bytes
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
或者使用推荐的pythonRequests Package,它有session objects,使用持久连接(使用urllib3)。