2012-12-14 36 views
2

我在學習Python。目前,我堅持用簡單的一件事:( 當我送與urllib2的請求時,它添加「連接:關閉」頭,我應該怎麼做派的請求沒有這個頭刪除HTTP「連接」標題,Python urllib2

我的代碼:?

request = urllib2.Request('http://example.com') 
request.add_header('User-Agent', self.client_list[self.client]) 
opener = urllib2.build_opener() 
opener.open(request).read() 

感謝球員,我非常以任何情況下urllib2感謝您的幫助

回答

5

而且不能從source code:。

# 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 library代替,它支持連接保持活動:

>>> 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標題。