一种http方式下载文件且支持重试的方法
private boolean httpDownloadOssFileUrl(String ossFileUrl, String path, String f) {
log.info("http下载文件-ossUrl:{}", ossFileUrl);
log.info("http下载文件-目标path:{}", path);
log.info("http下载文件-目标file:{}", f);
int maxRetries = 3;
int retries = 0;
boolean success = false;
while (retries < maxRetries && !success) {
log.info("第{}次下载!", retries + 1);
try {
URL url = new URL(ossFileUrl);
File file = new File(path, f);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", "NetFox");
int responseCode = httpURLConnection.getResponseCode();
log.info("responseCode:{}", responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
success = true;
InputStream inputStream = httpURLConnection.getInputStream();
try(FileOutputStream outputStream = new FileOutputStream(file)){
byte[] b = new byte[1024];
int nRead;
while ((nRead = inputStream.read(b, 0, 1024)) > 0) {
outputStream.write(b, 0, nRead);
}
log.info("OSS文件:{}下完了!", ossFileUrl);
inputStream.close();
}catch (Exception e){
log.error("下载oss文件失败", e);
}
}
} catch (Exception e) {
log.error("下载oss文件失败-ossUrl:{}", ossFileUrl);
log.error("下载oss文件失败", e);
}
retries++;
}
return success;
}