Comment utiliser Socks 5 proxy avec le Client HTTP Apache 4?
j'essaie de créer une application qui envoie HTTP
requests via Apache HC 4 via SOCKS5 proxy.
Je ne peux pas utiliser app-Global proxy, Car app est multi-threadée (j'ai besoin d'un proxy différent pour chaque instance HttpClient
). Je n'ai trouvé aucun exemple d'utilisation de SOCKS5 avec HC4. Comment puis-je l'utiliser?
3 réponses
SOCK est un protocole proxy de niveau TCP/IP, PAS HTTP. Il n'est pas pris en charge par HttpClient hors de la boîte.
on peut personnaliser HttpClient pour établir des connexions via un proxy SOCKS en utilisant une usine de socket de connexion personnalisée
EDIT: change 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);
}
}
la réponse ci-dessus fonctionne assez bien, à moins que votre pays empoisonne aussi DNS records. Il est très difficile de dire Java "n'utilisez pas mes serveurs DNS lors de la connexion par proxy" comme indiqué dans ces deux questions:
java runtime 6 avec proxy socks v5 - il Possible?
Comment obtenir une connexion URL en utilisant proxy en java?
il est également difficile pour Apache HttpClient, depuis qu'il essaie aussi de résoudre les noms d'hôtes localement. Par une modification du code ci-dessus, cela peut être traité comme suit:
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();
}
}
inspiré de la réponse de @oleg. Vous pouvez faire un utilitaire qui vous donne un Closeablhttpclient correctement configuré sans contraintes particulières sur la façon dont vous l'appelez.
vous pouvez utiliser le ProxySelector dans un ConnectionSocketFactory pour sélectionner le proxy.
Une classe utilitaire pour la construction de CloseableHttpClient instances:
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);
}
}
code Client utilisant:
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()));
}
}
}
}