你不能。urllib2
在任何情况下都不会。从源代码:
# We want to make an HTTP/1.1 request, but the addinfourl
# class isn't prepared to deal with a persistent connection.
# It will try to read all remaining data from the socket,
# which will block while the server waits for the next request.
# So make sure the connection gets closed after the (only)
# request.
headers["Connection"] = "close"
请改用该requests
库,它支持连接保持活动:
>>> import requests
>>> import pprint
>>> r = requests.get('http://httpbin.org/get')
>>> pprint.pprint(r.json)
{u'args': {},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate, compress',
u'Connection': u'keep-alive',
u'Content-Length': u'',
u'Content-Type': u'',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/0.14.1 CPython/2.6.8 Darwin/11.4.2'},
u'origin': u'176.11.12.149',
u'url': u'http://httpbin.org/get'}
上面的例子使用http://httpbin.org来反映请求头;如您所见,requests
使用了Connection: keep-alive
标题。