Search This Blog

Wednesday, August 10, 2011

How to add BASIC Authentication into HttpURLConnection?

Here is one sample.

...
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
...
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = username + ":" + password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+
encodedAuthorization);
...
//Send post data
...

} catch (Exception e) {
...
} finally {

if(connection != null) {
connection.disconnect();
}
}
}
...

2 comments:

Ava joseph said...

Nice Blog. This blog is very interesting and you are provide best information for users. I always visited your blog site.Thanks for your wonderful sharing.Liferay Development and Liferay Portal

Rajesh Developer said...

Very Interesting topic and usefull for every One and if you wants to learn some Core Java Interview Questions