我尝试使用以下代码在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?
答案 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标题。
答案 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