O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.10. Basic Authentication

Problem

You need to access information protected by HTTP Basic Authentication.

Solution

Create a UsernamePasswordCredentials object with a username and password. Add this Credentials object to the instance of HttpState associated with an HttpClient object. HttpClient will attempt to execute a message, and the server will respond with 401 response code; HttpClient will then retry the request with the appropriate Authorization header. The following example uses a UsernamePasswordCredentials object to access a protected resource:

               import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;

HttpClient client = new HttpClient( );
HttpState state = client.getState( );
    
// Set credentials on the client
Credentials credentials =
     new UsernamePasswordCredentials( "testuser", "crazypass" );
state.setCredentials( null, null, credentials );

String url = "http://www.discursive.com/jccook/auth/";
HttpMethod method = new GetMethod( url );
    
client.executeMethod( method );
String response = method.getResponseBodyAsString( );

System.out.println( response );
method.releaseConnection( );

This example executes a GetMethod, the server requests credentials, and the credentials are sent to the server. The final response ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required