Java笔记-使用RestTemplate下载大文件,并且设置下载时间

如果文件大,Java会报OOM(out of memory)。使用ResponseExtractor将远程服务器中的文件直接转成流存到文件中,而不放到内存。

事例代码如下:

@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 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 = "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");

如下:

这里可以在异常里面捕获,然后发送邮件,给客户,说着玩意下不下来。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值