HttpURLConnection in the JDK has a bizarre bug. When it receives a HTTP response code in the 3xx range, it performs redirection to the web page mentioned in the “Location” header. However, when it does this, it forgets to send all the cookies with the request. Therefore, if you are working with any of the web 2.0 APIs which perform redirection and require this authentication cookie with each request, you are doomed because the server will redirect to the login page thinking that this is an unauthenticated request.

The solution for this is pretty simple. If you have written code like below:

URL u = new URL(“http://www.example.com”);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

You have to add one more line that sets redirection to “FALSE” & do the redirection yourself with the cookies, which becomes like:

URL u = new URL(“http://www.example.com”);

HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.setInstanceFollowRedirects(false); // do not redirect

String locHeader = conn.getHeaderField(“Location”); // get the location

String cookies = conn.getHeaderField(“Set-Cookie”); // get the cookie

u = null; conn = null;

u = new URL(locHeader);

conn = (HttpURLConnection) u.openConnection();

conn.setRequestProperty(“Cookie”, cookies); // set the cookie yourself

….

Done! That should solve the bug. If this seems too much to do, then you should consider using this excellent HttpClient library from Apache.

I did the above mentioned stuff for this Free SMS Java Library because:

  1. The library has to be very small because it is just one file.
  2. Eliminate external dependencies that will bloat the library.
There you go! Now, if you have encountered this bug you have the solution to squash it. Have fun!

One Response to “HttpURLConnection.setFollowRedirects Bug”

  1. hasszhao Says:

    Hi , it may not be a bug.

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

    14.30 Location

    The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. For 201 (Created) responses, the Location is that of the new resource which was created by the request. For 3xx responses, the location SHOULD indicate the server’s preferred URI for automatic redirection to the resource. The field value consists of a single absolute URI.

    Location = “Location” “:” absoluteURI
    An example is:

    Location: http://www.w3.org/pub/WWW/People.html
    Note: The Content-Location header field (section 14.14) differs
    from Location in that the Content-Location identifies the original
    location of the entity enclosed in the request. It is therefore
    possible for a response to contain header fields for both Location
    and Content-Location. Also see section 13.10 for cache
    requirements of some methods.