11.13. Handling Redirects

Problem

You need to access a server that may send an arbitrary number of redirects.

Solution

Before executing an HttpMethod call, setFollowRedirects(true) on the method; HttpClient will take care of following any redirects a server may return in a response. The following example shows what happens when a method requests a CGI script that returns a 302 (moved temporarily) response code:

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

HttpClient client = new HttpClient( );
String url = "http://www.discursive.com/cgi-bin/jccook/redirect.cgi";
    
System.out.println( "Executing Method not following redirects: ");        
HttpMethod method = new GetMethod( url );
method.setFollowRedirects( false );
executeMethod(client, method);

System.out.println( "Executing Method following redirects: ");        
method = new GetMethod( url );
method.setFollowRedirects( true );
executeMethod(client, method);

private 
               static 
               void executeMethod(HttpClient client, HttpMethod method)
    throws IOException, HttpException {
    client.executeMethod( method );
    System.out.println( "Response Code: " + method.getStatusCode( ) );
    String response = method.getResponseBodyAsString( );
    System.out.println( response );
    method.releaseConnection( );
    method.recycle( );
}

This example executes two GetMethod instances; the first method is configured not to follow redirects, ...

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.