How can I configure HTTPClient to authenticate against a SOCKS proxy?

abahgat picture abahgat · Sep 7, 2009 · Viewed 22.6k times · Source

I need to set up proxy authentication against a SOCKS proxy. I found out this post giving instructions that appear to work with common HTTP proxies.

        httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);

        HttpState state = new HttpState();
        state.setProxyCredentials(new AuthScope("proxyserver.example.com", 8080), 
           new UsernamePasswordCredentials("username", "password"));
        httpclient.setState(state);

Would that work with SOCKS proxies as well or do I have to do something different?

Answer

tuergeist picture tuergeist · Sep 7, 2009

Java supports Socks proxy configuration via preferences:

  • socksProxyHost for the host name of the SOCKS proxy server
  • socksProxyPort for the port number, the default value being 1080

e.g.

java -DsocksProxyHost=socks.mydomain.com

(edit) For your example, if the socks proxy was configured in the way outlined before:

httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);
Credentials cred = new UsernamePasswordCredentials("username","password");
httpclient.getState().setProxyCredentials(AuthScope.ANY, cred); 

You can also use this variant (without httpclient):

SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); // Type.HTTP for HTTP

So completing the previous example, we can now add:

URL url = new URL("http://java.sun.com/");
URConnection conn = url.openConnection(proxy);

HTH