如何使用urllib在Python3.2中使用HTTP“Keep-Alive”

时间:2013-11-03 21:26:21

标签: urllib python-3.2

我尝试使用以下代码在Python 3.2.3中保持与urllib.request的HTTP连接:

handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(handler)
opener.addheaders = [("connection", "keep-alive"), ("Cookie", cookie_value)]
r = opener.open(url)

但是如果我听到与Wireshark的连接,我会得到一个标题为“Connection:closed”但是设置了Cookie。

Host: url
Cookie: cookie-value
Connection: close

如何将Headerinfo设置为Connection:keep-alive?

2 个答案:

答案 0 :(得分:1)

使用http-client

保持连接活跃
import http.client
conn = http.client.HTTPConnection(host, port)
conn.request(method, url, body, headers)

标题只是给dict而且正文仍然可以使用urllib.parse.urlencode。 所以,你可以通过http客户端制作Cookie标题。

参考:
official reference

答案 1 :(得分:0)

如果你需要比普通的http.client更自动的东西,这可能会有所帮助,虽然它不是线程安全的。

from http.client import HTTPConnection, HTTPSConnection
import select
connections = {}


def request(method, url, body=None, headers={}, **kwargs):
    scheme, _, host, path = url.split('/', 3)
    h = connections.get((scheme, host))
    if h and select.select([h.sock], [], [], 0)[0]:
        h.close()
        h = None
    if not h:
        Connection = HTTPConnection if scheme == 'http:' else HTTPSConnection
        h = connections[(scheme, host)] = Connection(host, **kwargs)
    h.request(method, '/' + path, body, headers)
    return h.getresponse()


def urlopen(url, data=None, *args, **kwargs):
    resp = request('POST' if data else 'GET', url, data, *args, **kwargs)
    assert resp.status < 400, (resp.status, resp.reason, resp.read())
    return resp