java.net.ProtocolException: Too many server redirects

2

I need to download a file .zip that can be found at the following address: link

For this I created the following method:

public static void downloadFile() throws IOException{
    final File file = new File("download/");
    if(!file.exists()){
        file.mkdirs();
    }
    final URL link = new URL(URL); 
    final InputStream in = new BufferedInputStream(link.openStream());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n = 0;
    while (-1!=(n=in.read(buf)))
    {
        out.write(buf, 0, n);
    }
    out.close();
    in.close();
    byte[] response = out.toByteArray();
    FileOutputStream fos = new FileOutputStream(PATH);
    fos.write(response);
    fos.close();
}

But when it runs link.openStream() , the following error occurs:

java.net.ProtocolException: Server redirected too many  times (20)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at good.dowload.DownloadManager.downloadFile(DownloadManager.java:31)
    at good.dowload.DownloadManager.main(DownloadManager.java:19)

How can I circumvent these redirects?

    
asked by anonymous 05.07.2015 / 02:30

1 answer

3

The problem is due to not keeping the user session, more or less what the browser does when you download there, if you disable the cookies in the browser you will notice the same error = )

As there are redirects on the server and by default the connection follows these redirects, due to the fact that you do not keep the user session is as if every time a new user / session (from the server point of view), what ends up generating infinite redirects.

The session is usually done with the help of a cookie , so you need to store the cookie to be used by the redirects, so we can even say that we will accept everything.

For this, simply add the following excerpt before you make your HTTP request:

CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

In some cases you will also need

See more details on managing cookies in the CookieManager .

    
05.07.2015 / 03:50