[英]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();
}
}
}
一個設定
連接.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.