HttpURLConnection not able to read 302 Response code

Viewed 33

I am trying to download a file through code and it is working if the file is found. But if the Link returns a 302 code, I am getting a connection timeout through code. It is working fine in browser.

Can someone help me out where I am going wrong?

My code is given below:

private static void downloadFile(String fileUrl, String fileName) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(fileUrl);

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
            connection.connect();

            int code = connection.getResponseCode();
            String message = connection.getResponseMessage();
            System.out.println(code + "-" + message);

            if (code == HttpURLConnection.HTTP_OK) {
                try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
                        FileOutputStream fileOutputStream = new FileOutputStream(fileName)) {
                    byte dataBuffer[] = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                        fileOutputStream.write(dataBuffer, 0, bytesRead);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                throw new Exception("Invalid Response Code: " + code + ", Response Message: " + message);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

Working URL(200): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo16SEP2022bhav.csv.zip

Timeout URL(302): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo17SEP2022bhav.csv.zip

1 Answers

A setting

connection.setInstanceFollowRedirects(true); // follow response codes 3xx

connection = (HttpURLConnection) new URL(fileUrl).openConnection();
connection.setInstanceFollowRedirects(true); // follow response codes 3xx
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
connection.connect();
Related