Monday, 13 April 2015

Authentication in Rest API using Apache HttpClient

In this post, I am going to share my experience related to Basic authorization of password protected rest api using Apache HttpClient.

Let me post the code that does the above activity:

                String username = "<uname>";
                String password = "<pwd>";
String domainURL = "com.test.domain";

String restPwdProtectedURL = "com.test.domain/password/protected";

String enc = username + ":" + password;

DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
HttpGet request = new HttpGet(restPwdProtectedURL);

request.addHeader("Authorization", "Basic " + new BASE64Encoder().encode(enc.getBytes()));
   httpResponse = client.execute(request);

Jars required:
1. apache-httpcomponents-httpclient.jar
2. apache-httpcomponent-httpcore.jar
3.commons-logging-1.2.jar
4. sun.misc.BASE64Decoder.jar

This is a simple program, so it does not require much explanation :-) Please let me know if there are any queries.

No comments:

Post a Comment