[英]Remove HTTP "Connection" header, Python urllib2
I'm trying to learn Python.我正在努力学习 Python。 At the moment I'm stuck with a simple thing:( When I send request with urllib2, it add "Connection:close" header. What should I do to send request WITHOUT this header?
目前我被一件简单的事情困住了:(当我用urllib2发送请求时,它添加了“Connection:close”标头。如果没有这个标头,我应该怎么做才能发送请求?
My code:我的代码:
request = urllib2.Request('http://example.com')
request.add_header('User-Agent', self.client_list[self.client])
opener = urllib2.build_opener()
opener.open(request).read()
Thanks guys, I'm very appreciate your help!谢谢你们,我非常感谢你们的帮助!
You can't.你不能。 Not with
urllib2
in any case.在任何情况下都不适用于
urllib2
。 From the 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"
Use the requests
library instead, it supports connection keep-alive:请改用
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'}
The above example uses http://httpbin.org to reflect the request headers;上面的示例使用http://httpbin.org来反映请求标头; as you can see
requests
used a Connection: keep-alive
header.如您所见,
requests
使用了Connection: keep-alive
标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.