Java如何使用RestTemplate下载大文件(并设置下载时间)呢?
下文笔者讲述RestTemplate下载大文件的方法及示例分享,如下所示
当我们下载大文件时,有时会报OOM(out of memory)
那么此时我们 应该如何处理呢?
我们需
使用ResponseExtractor将远程服务器中的文件直接转成流存到文件中
而不应该放到内存中
RestTemplate下载大文件的示例
@GetMapping("/test-download-v3")
public void downloadFile() throws IOException {
String url = "https://img.java265.com/test.jpg";
// Optional Accept header
RequestCallback requestCallback = request -> request
.getHeaders()
.setAccept(Arrays.aslist(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
// Streams the response instead of loading it all in memory
ResponseExtractor<Void> responseExtractor = response -> {
// Here you can write the inputstream to a file or any other place
Path path = Paths.get("downloadv3.jpg");
Files.copy(response.getBody(), path);
return null;
};
restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
}
有些网站
刚开始是1MB/s
后面直接是1B/s
此时需设置下载时间
如:
5分钟没下载好,就禁止下载
String url = "https://img.java265.com/test.jpg";
SimpleClientHttpRequestFactory httpFactory = new SimpleClientHttpRequestFactory();
httpFactory.setReadTimeout(1);
restTemplate.setRequestFactory(httpFactory);
try{
RequestCallback requestCallback = request -> request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
ResponseExtractor<Void> responseExtractor = response -> {
Path path = Paths.get("D:\\test.jpg");
Files.copy(response.getBody(), path);
return null;
};
restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
}
catch (Exception e){
e.printStackTrace();
}
finally {
}
System.out.println("下载超时!");
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


