1

通常,当使用 httplib (python 2.x) 或 http.client (python 3.x) 时,您会建立一个连接并发出如下请求:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

url = urlparse("http://final.destination.example.com:8888/")
conn = HTTPConnection(url.netloc)
request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)

(请注意,此示例代码具有 python 3.x 导入)

我处于一种出于性能原因想使用 http.client 的情况,但我也想使用 SOCKS 代理远程访问集群。

有什么方法可以将 SOCKS 代理与 httplib/http.client 一起使用?

4

1 回答 1

2

我在这里回答我自己的问题,希望这种情况下的下一个人能找到解决方案。

首先安装 PySocks:

pip install PySocks

然后你需要在实例化你的 HTTPConnection 并通知它它将使用代理之后手动设置你的 SOCKS 代理:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)
于 2017-07-03T21:18:21.723 回答