Getting “java.net.ProtocolException: Server redirected too many times” Error

It’s apparently redirecting in an infinite loop because you don’t maintain the user session. The session is usually backed by a cookie. You need to create a CookieManager before you use URLConnection.

// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

See also:

  • Using java.net.URLConnection to fire and handle HTTP requests

Leave a Comment