Thursday, July 31, 2014

How to configure http proxy and its credentials in java code

When your computer is behind a proxy server and if you are trying to access URLs outside of your network though java code , then you might get network errors similar to below.

Caused by: java.net.ConnectException: Connection timed out: connect
 at java.net.PlainSocketImpl.socketConnect(Native Method)

If you are executing your program in eclipse or any other IDE, then you can set proxy details there in Windows --> Preferences --> General --> Network Connections.

But if you are connected to a VPN , and if VPN is using proxy server, then setting proxy servers details in eclipse IDE will not help.
In this case you will still get issues in connecting to remote server.

You have to fix this in code itself. Add below code to you java file. modify proxy server address, proxy port, username and password and try it out.
This proxy settings will also work even if you are not using any IDE like eclipse.

static
{
 Authenticator.setDefault(new ProxyAuthenticator("username", "password"));
 System.setProperty("http.proxyHost", "proxy host address");
 System.setProperty("http.proxyPort", "proxy port");
}

static class ProxyAuthenticator extends Authenticator 
{
 private String user, password;

 public ProxyAuthenticator(String user, String password) 
 {
  this.user = user;
     this.password = password;
 }

 protected PasswordAuthentication getPasswordAuthentication() 
 {
  return new PasswordAuthentication(user, password.toCharArray());
 }
}

Following import will be required.

import java.net.Authenticator;

If you are using Apache HttpClient to access URL outside of your proxy server, then above code might not work. In that case, you have to set proxy configuration in HttpClient object as in below code snippet.

httpclient.getHostConfiguration().setProxy("proxyserver.example.com", 8080);
Credentials cred = new UsernamePasswordCredentials("username","password");
httpclient.getState().setProxyCredentials(AuthScope.ANY, cred);

If you are using an android device or emulator, then you can set proxy settings in code as below.

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000*15);
HttpConnectionParams.setSoTimeout(httpParams, 1000*15);

HttpHost proxy = new HttpHost("your proxy server", 80);
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new NTCredentials("your_username", "your_password", null, null));

httpClient.setParams(httpParams);

Creating and Deploying Java Web Application on AWS using Elastic Beanstalk

This tutorial is for creating simple java web application using eclipse and then deploying it on AWS cloud. Video tutorial for creating/de...