如何在 Apache HTTP Client 4 中使用 Socks 5 代理? [英] How to use Socks 5 proxy with Apache HTTP Client 4?

查看:60
本文介绍了如何在 Apache HTTP Client 4 中使用 Socks 5 代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建通过 SOCKS5 代理通过 Apache HC 4 发送 HTTP 请求的应用程序.我不能使用应用全局代理,因为应用是多线程的(我需要为每个 HttpClient 实例使用不同的代理).我没有发现 SOCKS5 与 HC4 一起使用的例子.我该如何使用它?

I'm trying to create app that sends HTTP requests via Apache HC 4 via SOCKS5 proxy. I can not use app-global proxy, because app is multi-threaded (I need different proxy for each HttpClient instance). I've found no examples of SOCKS5 usage with HC4. How can I use it?

推荐答案

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

SOCK is a TCP/IP level proxy protocol, not HTTP. It is not supported by HttpClient out of the box.

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

One can customize HttpClient to establish connections via a SOCKS proxy by using a custom connection socket factory

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

changes to SSL instead of plain sockets

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 代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆