如何在Apache HTTP Client 4中使用Socks 5代理?

我正在尝试创建通过 HC

发送HTTP请求的应用。我无法使用应用程序全局代理,因为应用程序是多线程的(我需要为每个实例使用不同的代理)。我没有发现HC4使用SOCKS5的示例。如何使用?

*HttpClient

回答:

SOCK是TCP / IP级别的代理协议,而不是HTTP。开箱即用不支持HttpClient。

可以使用自定义连接套接字工厂自定义HttpClient以通过SOCKS代理建立连接

更改为SSL而不是普通套接字

Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()

.register("http", PlainConnectionSocketFactory.INSTANCE)

.register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))

.build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);

CloseableHttpClient httpclient = HttpClients.custom()

.setConnectionManager(cm)

.build();

try {

InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);

HttpClientContext context = HttpClientContext.create();

context.setAttribute("socks.address", socksaddr);

HttpHost target = new HttpHost("localhost", 80, "http");

HttpGet request = new HttpGet("/");

System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);

CloseableHttpResponse response = httpclient.execute(target, request, context);

try {

System.out.println("----------------------------------------");

System.out.println(response.getStatusLine());

EntityUtils.consume(response.getEntity());

} finally {

response.close();

}

} finally {

httpclient.close();

}


static class MyConnectionSocketFactory extends SSLConnectionSocketFactory {

public MyConnectionSocketFactory(final SSLContext sslContext) {

super(sslContext);

}

@Override

public Socket createSocket(final HttpContext context) throws IOException {

InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");

Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);

return new Socket(proxy);

}

}

以上是 如何在Apache HTTP Client 4中使用Socks 5代理? 的全部内容, 来源链接: utcz.com/qa/418276.html

回到顶部