code: public URLConnection connectWithRedirect(URL theURL) throws IOException {
          URLConnection conn = null;
  
          String accept_header = buildAcceptHeader();
          int redirect_count = 0;
          boolean done = false;
  
          while (!done) {
              if (theURL.getProtocol().equals("file")) {
                  return null;
              }
              Boolean isHttp = (theURL.getProtocol().equals("http") || theURL
                      .getProtocol().equals("https"));
  
              logger.debug("Requesting: " + theURL.toString());
  
              conn = theURL.openConnection();
  
              if (isHttp) {
                  logger.debug("Accept: " + accept_header);
                  conn.setRequestProperty("Accept", accept_header);
              }
  
              conn.setConnectTimeout(60000);
              conn.setReadTimeout(60000);
  
              conn.connect();
  
              done = true; // by default quit after one request
  
              if (isHttp) {
                  logger.debug("Response: " + conn.getHeaderField(0));
                  int rc = ((HttpURLConnection) conn).getResponseCode();
  
                  if ((rc == HttpURLConnection.HTTP_MOVED_PERM)
                          || (rc == HttpURLConnection.HTTP_MOVED_TEMP)
                          || (rc == HttpURLConnection.HTTP_SEE_OTHER)
                          || (rc == 307)) {
                      if (redirect_count > 10) {
                          return null; // Error: too many redirects
                      }
                      redirect_count++;
                      String loc = conn.getHeaderField("Location");
                      if (loc != null) {
                          theURL = new URL(loc);
                          done = false;
                      } else {
                          return null; // Bad redirect
                      }
                  } else if ((rc < 200) || (rc >= 300)) {
                      return null; // Unsuccessful
                  }
              }
          }
          return conn;
      }
docs: A method to connect to a URL and follow redirects if any.
  @param theURL a URL to connect to
  @return a {@link URLConnection}
  @throws IOException if connection cannot be opened and no response is received.