使用python请求添加代理头

2024-05-15 22:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

规范:Python2.7.9,Requests 2.12.4,Windows操作系统

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)

问题: 我需要向httpconnect方法添加一个“HOST”头。请求或urllib3似乎没有发送此标头,也没有采用代理服务器不排除的格式;“Host”:api.ipify.org网站". 添加一个主机头是解决方案,但我不确定最好的方法是什么。在


Tags: 方法httpsorgip规范apihttpurl
1条回答
网友
1楼 · 发布于 2024-05-15 22:30:34

您不能通过请求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

相关问题 更多 >