gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:04 25 4
gpt4 key购买 nike

我尝试使用以下代码在 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 监听连接,我会得到一个带有“连接:已关闭”的 header ,但设置了 Cookie。

Host: url
Cookie: cookie-value
Connection: close

我需要做什么才能将 Headerinfo 设置为 Connection: keep-alive?

最佳答案

如果您需要比普通 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

关于urllib - 如何在Python3.2中使用urllib HTTP 'Keep-Alive',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com