开发者

How to use SOCKS in Java?

I use 100% working socks and I can't connect through my application.

        SocketAddress proxyAddr = new InetSocketAddress("1.1.1.1", 12345);
        Proxy pr = new Proxy(Proxy.Type.SOCKS, proxyAddr);

    try
    {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(pr);
        con.setConnectTimeout(proxyTimeout * 1000);
        con.setReadTimeout(proxyTimeout * 1000);
        con.connect();

        System.out.println(con.usingProxy());
    }
    catch(IOException ex)
    {
开发者_StackOverflow中文版        Logger.getLogger(Enter.class.getName()).log(Level.SEVERE, null, ex);
    }

So what am I doing wrong? If I'll use HTTP with some HTTP proxy all is working but not with SOCKS.


It's really easy. You just need to set the relevant System Properties and just get on with your regular HttpConnection.

System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "socksProxyHost", "127.0.0.1" );
System.getProperties().put( "socksProxyPort", "1234" );


Inform the "socksProxyHost" and "socksProxyPort" VM arguments.

e.g.

java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main


http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/sun/net/www/http/HttpClient.java/?v=source

Deep down, HttpClient is used in HttpURLConnection.

if ((proxy != null) && (proxy.type() == Proxy.Type.HTTP)) {
   sun.net.www.URLConnection.setProxiedHost(host);
   privilegedOpenServer((InetSocketAddress) proxy.address());
   usingProxy = true;
   return;
} else {
   // make direct connection
   openServer(host, port);
   usingProxy = false;
   return;
}

On line 476, you can see that the only acceptable proxy is an HTTP proxy. It makes a direct connection otherwise.

Weirdly there's is no support for SOCKS proxy using HttpURLConnection. Even worse, the code doesn't even t using an unsupported proxy and just ignores the proxy!

Why there isn't any support for SOCKS proxies after at least 10 years of this class' existence cannot be explained.


Or this answer: https://stackoverflow.com/a/64649010/5352325

If you know which URIs need to go to proxy, you can also use the low layer ProxySelector: https://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html where for each Socket connection that is made, you can decide what proxies are to be used.

It looks something like this:

public class MyProxySelector extends ProxySelector {
        ...

        public java.util.List<Proxy> select(URI uri) {
        ...
          if (uri is what I need) {
             return list of my Proxies
          }
        ...
        }
        ...
}
 

Then you make use of your selector:

public static void main(String[] args) {
        MyProxySelector ps = new MyProxySelector(ProxySelector.getDefault());
        ProxySelector.setDefault(ps);
        // rest of the application
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜