java.net.Protocolexception: many server redirects

Asked

Viewed 392 times

2

I need to download a file .zip which is located at the following address: http://www1.caixa.gov.br/lotteries/lotteries/lotteries/D_quina.zip

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 he executes the 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 bypass these redirects?

1 answer

3


The problem is due to not keeping user session, more or less what the browser does when you download from there, if you disable the cookies in the browser will realize 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’s session is as if every time it was a new user/session (from the server’s point of view), which ends up generating infinite redirects.

The session is usually done with the help of a cookie, then you need to store the cookie so that it is used for redirects, so we can really say that we will accept everything.

For this, just add the following snippet before making your HTTP request:

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

In some cases you will also need

See more details about managing cookies in the documentation of CookieManager.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.