14 Jan 2009

Make HTTP request with authentication using JAVA

Here is an example on how to make an http request to a page that requires authentication using Java language.


// Create the connection
URL url = new URL (urlStr);
URLConnection uc = url.openConnection();

// Prepare authentication data
String authData = username + ":" + password;
String encodedAuthData = new sun.misc.BASE64Encoder().encode (authData.getBytes());
// Set authentication data
uc.setRequestProperty ("Authorization", "Basic " + encodedAuthData);

// Get the contents
InputStream is = uc.getContent();

No comments: