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();
}
}
}
...

1 comment:

Unknown said...

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