How to use SOCKS in Java?

Clark picture Clark · Apr 18, 2011 · Viewed 25k times · Source

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)
    {
        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.

Answer

2hamed picture 2hamed · Aug 25, 2012

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" );