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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22937983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:26:21  来源:igfitidea点击:

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

javadnsapache-httpclient-4.xsocks

提问by user3511070

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

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

采纳答案by ok2c

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

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

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

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

EDIT:changes to SSL instead of plain sockets

编辑:更改为 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);
    }

}

回答by b10y

The answer above works pretty well, unless your country poisons DNS records as well. It is very difficult to say Java "do not use my DNS servers while connecting through proxy" as addressed in these two questions:

上面的答案非常有效,除非您的国家/地区也对 DNS 记录进行了毒害。如以下两个问题所述,很难说 Java“在通过代理连接时不使用我的 DNS 服务器”:

java runtime 6 with socks v5 proxy - Possible?

带有socks v5代理的java runtime 6 - 可能吗?

How to get URL connection using proxy in java?

如何在java中使用代理获取URL连接?

It is also difficult for Apache HttpClient, since it also tries to resolve host names locally. By some modification to the code above, this can be dealt with:

对于 Apache HttpClient 来说也很困难,因为它也尝试在本地解析主机名。通过对上面的代码进行一些修改,可以解决这个问题:

static class FakeDnsResolver implements DnsResolver {
    @Override
    public InetAddress[] resolve(String host) throws UnknownHostException {
        // Return some fake DNS record for every request, we won't be using it
        return new InetAddress[] { InetAddress.getByAddress(new byte[] { 1, 1, 1, 1 }) };
    }
}

static class MyConnectionSocketFactory extends PlainConnectionSocketFactory {
    @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);
    }

    @Override
    public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,
            InetSocketAddress localAddress, HttpContext context) throws IOException {
        // Convert address to unresolved
        InetSocketAddress unresolvedRemote = InetSocketAddress
                .createUnresolved(host.getHostName(), remoteAddress.getPort());
        return super.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context);
    }
}

static class MySSLConnectionSocketFactory extends SSLConnectionSocketFactory {

    public MySSLConnectionSocketFactory(final SSLContext sslContext) {
        // You may need this verifier if target site's certificate is not secure
        super(sslContext, ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    @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);
    }

    @Override
    public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,
            InetSocketAddress localAddress, HttpContext context) throws IOException {
        // Convert address to unresolved
        InetSocketAddress unresolvedRemote = InetSocketAddress
                .createUnresolved(host.getHostName(), remoteAddress.getPort());
        return super.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context);
    }
}


public static void main(String[] args) throws Exception {
    Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", new MyConnectionSocketFactory())
            .register("https", new MySSLConnectionSocketFactory(SSLContexts.createSystemDefault())).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg, new FakeDnsResolver());
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {
        InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
        HttpClientContext context = HttpClientContext.create();
        context.setAttribute("socks.address", socksaddr);

        HttpGet request = new HttpGet("https://www.funnyordie.com");

        System.out.println("Executing request " + request + " via SOCKS proxy " + socksaddr);
        CloseableHttpResponse response = httpclient.execute(request, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            int i = -1;
            InputStream stream = response.getEntity().getContent();
            while ((i = stream.read()) != -1) {
                System.out.print((char) i);
            }
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

回答by Alain O'Dea

Inspired by @oleg's answer. You can make a utility that gives you a properly configured CloseableHttpClient with no special constraints on how you call it.

灵感来自@oleg 的回答。您可以制作一个实用程序,为您提供正确配置的 CloseableHttpClient,对您的调用方式没有特殊限制。

You can use the ProxySelector in a ConnectionSocketFactory to select the proxy.

您可以使用 ConnectionSocketFactory 中的 ProxySelector 来选择代理。

A utility class for constructing CloseableHttpClient instances:

用于构造 CloseableHttpClient 实例的实用程序类:

import org.apache.http.HttpHost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.*;

public final class HttpHelper {
    public static CloseableHttpClient createClient()
    {
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", ProxySelectorPlainConnectionSocketFactory.INSTANCE)
                .register("https", new ProxySelectorSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
        return HttpClients.custom()
                .setConnectionManager(cm)
                .build();
    }

    private enum ProxySelectorPlainConnectionSocketFactory implements ConnectionSocketFactory {
        INSTANCE;

        @Override
        public Socket createSocket(HttpContext context) {
            return HttpHelper.createSocket(context);
        }

        @Override
        public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException {
            return PlainConnectionSocketFactory.INSTANCE.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
        }
    }

    private static final class ProxySelectorSSLConnectionSocketFactory extends SSLConnectionSocketFactory {
        ProxySelectorSSLConnectionSocketFactory(SSLContext sslContext) {
            super(sslContext);
        }

        @Override
        public Socket createSocket(HttpContext context) {
            return HttpHelper.createSocket(context);
        }
    }

    private static Socket createSocket(HttpContext context) {
        HttpHost httpTargetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        URI uri = URI.create(httpTargetHost.toURI());
        Proxy proxy = ProxySelector.getDefault().select(uri).iterator().next();
        return new Socket(proxy);
    }
}

Client code using that:

使用它的客户端代码:

import com.okta.tools.helpers.HttpHelper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws IOException {
        URI uri = URI.create("http://example.com/");
        HttpGet request = new HttpGet(uri);
        try (CloseableHttpClient closeableHttpClient = HttpHelper.createClient()) {
            try (CloseableHttpResponse response = closeableHttpClient.execute(request)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            }
        }
    }
}