How to use Socks 5 proxy with Apache HTTP Client 4?

后端 未结 4 547
南旧
南旧 2020-12-08 05:03

I\'m trying to create app that sends HTTP requests via Apache HC 4 via SOCKS5 proxy. I can not use app-global

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 05:52

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

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

    EDIT: changes to SSL instead of plain sockets

    Registry reg = RegistryBuilder.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);
        }
    
    }
    

提交回复
热议问题