Introduction

This document provides a brief guide to handling cross host redirects with HttpClient . In future versions, it is anticipated that this will be handled by the HttpClient class automatically. However due to technical constraints and the desire to stabilise the API for a 2.0 release sooner rather than later, this ability is yet to be implemented. Redirects to a different URL on the same host, port and protocol is supported.

Handling Redirects

When a server returns a redirect instruction to HttpClient that requires connecting to a different host, HttpClient will simply return the redirect status code as the response status. This will be one of:

  • 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
  • 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
  • 303 See Other. HttpStatus.SC_SEE_OTHER
  • 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT

When your application receives one of these codes, it should extract the new URL from the HttpMethod object and retry downloading from that URL. Additionally, it is usually a good idea to limit the number of redirects that will be followed in the redirects point to each other.

The URL to connect to can be extracted from the Location header.

        String redirectLocation;
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
        } else {
            // The response is invalid and did not provide the new location for
            // the resource.  Report an error or possibly handle the response
            // like a 404 Not Found error.
        }
      

Once you have determined the new location, you can reattempt the connection as normal. See the Tutorial for more information on this.