2

我正在努力学习 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()

谢谢大家,非常感谢您的帮助!

4

1 回答 1

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"

请改用该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标题。

于 2012-12-14T15:28:14.563 回答