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 ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.