Java笔记-使用RestTemplate下载大文件,并且设置下载时间
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-使用RestTemplate下载大文件,并且设置下载时间
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如果文件大,Java會(huì)報(bào)OOM(out of memory)。使用ResponseExtractor將遠(yuǎn)程服務(wù)器中的文件直接轉(zhuǎn)成流存到文件中,而不放到內(nèi)存。
事例代碼如下:
@GetMapping("/test-download-v3") public void downloadFile() throws IOException {String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg";// Optional Accept headerRequestCallback requestCallback = request -> request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));// Streams the response instead of loading it all in memoryResponseExtractor<Void> responseExtractor = response -> {// Here you can write the inputstream to a file or any other placePath path = Paths.get("downloadv3.jpg");Files.copy(response.getBody(), path);return null;};restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor); }這里要注意的是,有些廠家提供的下載,剛開(kāi)始是1MB/s,后面直接是1B/s,簡(jiǎn)直是坑,對(duì)此,要設(shè)置下下載時(shí)間,比如5分鐘沒(méi)下載好,就不下了。
String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.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("C:\\Users\\cff\\Desktop\\downloadv3.jpg");Files.copy(response.getBody(), path);return null;};restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);}catch (Exception e){e.printStackTrace();}finally {}System.out.println("over");如下:
這里可以在異常里面捕獲,然后發(fā)送郵件,給客戶,說(shuō)著玩意下不下來(lái)。
?
總結(jié)
以上是生活随笔為你收集整理的Java笔记-使用RestTemplate下载大文件,并且设置下载时间的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: tga格式转化为jpg格式
- 下一篇: java美元兑换,(Java实现) 美元