删除HTTP"连接"标头,Python urllib2

Ser*_*rge 2 python header urllib2

我正在努力学习Python.目前我遇到了一件简单的事情:(当我用urllib2发送请求时,它会添加"Connection:close"标题.如果没有这个标题,我该怎么办?

我的代码:

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

谢谢你们,我非常感谢你的帮助!

Mar*_*ers 5

你不能.不与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"
Run Code Online (Sandbox Code Playgroud)

而是使用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'}
Run Code Online (Sandbox Code Playgroud)

上面的示例使用http://httpbin.org来反映请求标头; 你可以看到requests使用了Connection: keep-alive标题.