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

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