Thursday 12 April 2012

Java bypass proxy with code

Setting proxy in / with java code

As We normally use httpconenction class for url connection. Sometimes it can create problem, specially
when you are working in a System in which internet is blocked by any proxy. So you have to authenticate yourself by giving username and password .

Before your credentials you need to tell JVM which proxy you have and it is running on which port. This can be accomplished by following two lines.

   System.setProperty("http.proxyHost", PROXY);
            System.setProperty("http.proxyPort", PROXY_PORT);

Now we need to authenticate ourselves which can be done by using simple one line code given below :

            Authenticator.setDefault(new MyAuthenticator());

Here MyAuthenticator is authenticator class used to authenticate user, username and password, just
overide getPasswordAuthentication() function, i.e :


public class MyAuthenticator extends Authenticator {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("UserName", "Password".toCharArray());
    }
}


Copy and paste above Authenticator class in your project and replace username and password with yours.

                     Note:  Do all above task before making your URLConnection

No comments:

Post a Comment