July 10, 2013

How to set HTTP proxy settings to run java program?

It is quite common that the corporate companies configure their network behind the proxy so that it will add a level of security to the network. For employees to access the resources (websites) outside the network they have to go via proxy server. For example if you are writing a java program to read the html content from a web page and you are executing the program from your PC which is behind the proxy. You cannot directly access the URL in your java code and you may get the exception saying "Connection Refused". For that you need to set the HTTP proxy settings in your code.

You can do it in two ways:

Via Command Line as JVM arguments:

java -Dhttp.proxyHost=proxyServerIPorHostName
-Dhttp.proxyPort=proxyServerPort
-Dhttp.proxyUser=userName
-Dhttp.proxyPassword=password HelloWorldProgram

As System properties in Java program:

System.getProperties().put("http.proxyHost", "proxyServerIPorHostName");
System.getProperties().put("http.proxyPort", "proxyServerPort");

final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
   new Authenticator() {
      public PasswordAuthentication getPasswordAuthentication() {
         return new PasswordAuthentication(
               authUser, authPassword.toCharArray());
      }
   }
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

set the above properties in your java code before accessing any network resources outside your corporate intranet.


No comments:

Post a Comment