I'm trying to open a URL using HttpURLConnection, but the page that I'm looking at has a redirect instruction.

Tim Rohaly

The HTTP specification states:

A user agent SHOULD NOT automatically redirect a request more than 5 times, since such redirections usually indicate an infinite loop.
The user agent you're using is here is HttpURLConnection, which strictly adheres to this limit. The fact that you're getting that error message indicates there's something wrong with the site setup - you should have the webmaster fix this.

setFollowRedirects() just controls the automatic following of redirects - you can also follow redirects manually, by reading the "Location" header of the HTTP response to obtain the new URL then using a new instance of HttpURLConnection to open that new URL. The example below shows code which prints out what URL you are being redirected to, along with some sample output.

import java.net.*;

public class ShowRedirect {

    public static void main(String[] args) throws Exception {
        URL url = new URL(args[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        System.out.println("Response code = " + connection.getResponseCode());
        String header = connection.getHeaderField("location");
        if (header != null)
            System.out.println("Redirected to " + header);
Using this to access the jGuru web site, we find:
> java ShowRedirect http://www.jguru.com/
Response code = 302
Redirected to http://www.jguru.com/portal/index.jsp?tab=8