gpt4 book ai didi

python - 使用python请求添加代理 header

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:30 25 4
gpt4 key购买 nike

规格:Python 2.7.9,请求2.12.4,Windows OS

s = requests.Session()
proxy = {'http':'http://ip:port',
'https':'http://ip:port'}
r_url = "https://api.ipify.org"
s.get(r_url,verify=False,timeout=5,proxies=proxy,headers=headers)


问题:
我需要向HTTP CONNECT方法添加“ HOST”标头。似乎请求或urllib3都没有发送此标头或代理服务器没有例外的格式;“主机”:“ api.ipify.org”。添加主机头是解决方案,但是我不确定最好的解决方法是什么。

最佳答案

您无法通过请求AFAIK来执行此操作,而必须进一步降低urrllib2的级别:

class ProxyHTTPConnection(httplib.HTTPConnection):

_ports = {'http' : 80, 'https' : 443}


def request(self, method, url, body=None, headers={}):
#request is called before connect, so can interpret url and get
#real host/port to be used to make CONNECT request to proxy
proto, rest = urllib.splittype(url)
if proto is None:
raise ValueError, "unknown URL type: %s" % url
#get host
host, rest = urllib.splithost(rest)
#try to get port
host, port = urllib.splitport(host)
#if port is not defined try to get from proto
if port is None:
try:
port = self._ports[proto]
except KeyError:
raise ValueError, "unknown protocol for: %s" % url
self._real_host = host
self._real_port = port
httplib.HTTPConnection.request(self, method, url, body, headers)


def connect(self):
httplib.HTTPConnection.connect(self)
#send proxy CONNECT request
self.send("CONNECT %s:%d HTTP/1.0\r\n\r\n" % (self._real_host, self._real_port))
#expect a HTTP/1.0 200 Connection established
response = self.response_class(self.sock, strict=self.strict, method=self._method)
(version, code, message) = response._read_status()
#probably here we can handle auth requests...
if code != 200:
#proxy returned and error, abort connection, and raise exception
self.close()
raise socket.error, "Proxy connection failed: %d %s" % (code, message.strip())
#eat up header block from proxy....
while True:
#should not use directly fp probably
line = response.fp.readline()
if line == '\r\n': break

关于python - 使用python请求添加代理 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689688/

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