Search code examples
javaproxyhttpurlconnectionsocksauthenticator

Java - how to setup socks proxy with credentials


Hi There Dear Community Members, i am a begginer and i am trying to setup a socks proxy with credentials so i used the following code. but it's not working.

proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("myhost.com", 81));
Authenticator.setDefault(new ProxyAuthenticator("aaa","aaa"));
conn = (HttpURLConnection) url.openConnection(proxy);

i am getting error

java.net.SocketException: SOCKS : authentication failed

i even tried the following code but its not working too.

proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("myhost.com", 81));
System.setProperty("java.net.socks.username","aaa");
System.setProperty("java.net.socks.password","aaa");

i tried to combine them, i tried to use System.setProperty("socksProxyUser","aaa") and System.setProperty("socksProxyPassword","aaa") but i am still getting the same error. Can Anyone Please Help me.

Thanks in Advance


Solution

  • Try this when attempting to authenticate.

    public Authenticator getAuth(String user, String password) {
        new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return (new PasswordAuthentication(user, password.toCharArray()));
            }
        };
    }
    

    Then, normally initialize your proxy Like how youre doing, except with the authentication (The reason why youre getting an error), do this.

    Authenticator.setDefault(getAuth(username, password));