java.net.ProtocolException: Server redirected too many times(20)

  • Post author:
  • Post category:java


If the above doesn’t apply, you may try to use the following code (hack) to skip the re-direction,

get the Location header and re-connect:

try {


URL url = new URL(“http://www.ama.org/events “);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setFollowRedirects(true);

con.setInstanceFollowRedirects(false);

con.connect();

while (String.valueOf(con.getResponseCode()).startsWith(“3”)) {


String theLocation = con.getHeaderField(“Location”);

con.disconnect();

url = new URL(theLocation);

con = (HttpURLConnection) url.openConnection();

con.setFollowRedirects(true);

con.setInstanceFollowRedirects(false);

con.connect();

}

/** at this point you are located at the last(target)page of

redirection chain */

} catch (Exception ex) { ex.printStackTrace(); }