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

Java Client http / https connection

Hi,

If you are facing as simple problem as hitting an URL through java code and getting response back, you are at right place. It is damn simple. Just follow steps given below :

1 ) Include myclient.jar file in your project.  click here to download jar file

2) Make an object of ClientURLConnection.

3) Pass URL you want to hit.

3) Set method you want to send request (GET or POST)

4) Add parameters (key-value pair) , if any you want to send along with request.

5) Call method yourObject.getInputStream()

And it is done !! Now do not waste time here and complete your task :)