簡體   English   中英

HttpURLConnection 無法讀取 302 響應代碼

[英]HttpURLConnection not able to read 302 Response code

我正在嘗試通過代碼下載文件,如果找到該文件,它就可以工作。 但如果鏈接返回 302 代碼,我會通過代碼獲得連接超時。 它在瀏覽器中運行良好。

有人可以幫我解決我哪里出錯了嗎?

我的代碼如下:

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();
            }
        }
    }

工作網址(200): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo16SEP2022bhav.csv4172F2229BA9A2D8

超時 URL(302): https://archives.nseindia.com/content/historical/DERIVATIVES/2022/SEP/fo17SEP2022bhav.Z628CB5675FF524F3E719B7AA2E88FE3FA48172F222Z9B19D

一個設定

連接.setInstanceFollowRedirects(true); // 跟隨響應代碼 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM