Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpUrlConnection proxy authentication gets into redirect loop

I am trying to get contents of an URL through an authenticated proxy. This is the code i am trying to use:

        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                System.out.println("authenticating");
                return (new PasswordAuthentication("username", "password".toCharArray()));
            }
        };
        Authenticator.setDefault(authenticator);
        URL url = new URL("http://www.google.com");
        InetSocketAddress proxyAddress = new InetSocketAddress("address.of.proxy", 6060);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
        uc.connect();
        System.out.println(uc.getResponseCode());

For some reason, the authentication gets into a redirect loop, so the result is the authenticator printing "authenticating" 20 times, then a ProtocolException

java.net.ProtocolException: Server redirected too many  times (20)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1846)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at java.net.URLConnection.getContent(URLConnection.java:739)
at proxytest.RunThis.main(RunThis.java:29)

The proxy is working with the given credentials, i have tried it through browser. I am trying to get this working for days, i have tried setting system properties, apache httpclient, and anything i could get out of google. Any ideas appreciated. :)

UPDATE:

I tested with WireShark, the proxy authentication details are in the request, but the proxy throws back a 407 error. Again, the credentials are OK, its working perfectly from browser ( i actually copied them from the source code to make sure ).

There is one thing i noticed though. The value of the Proxy-Authorization header differs in one and only one character between the browser and the request sent by java. Can this mean something?

like image 485
Koocka Avatar asked Oct 31 '22 05:10

Koocka


1 Answers

The Authenticator.setDefault(authenticator); must be after the openConnection(proxy);

URL url = new URL("http://www.google.com");
InetSocketAddress proxyAddress = new InetSocketAddress("address.of.proxy", 6060);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
HttpURLConnection uc = (HttpURLConnection) url.openConnection(proxy);
    Authenticator.setDefault(new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("username", "password".toCharArray()));
          }
        });
uc.connect();
System.out.println(uc.getResponseCode());
like image 126
Andres Robles Avatar answered Nov 15 '22 06:11

Andres Robles