首页 > 解决方案 > 用springboot resttemplate下载一个文件

问题描述

我使用此代码下载文件:

HttpHeaders httpHeaders = recuperaHeaders();
            File file = restTemplate.execute(url, HttpMethod.GET, null, clientHttpResponse -> {
                File ret = File.createTempFile("download", ".PDF");
                InputStream body = clientHttpResponse.getBody();
                StreamUtils.copy(body, new FileOutputStream(ret));
                return ret;
            });
            return file;

但是调用返回 302(重定向)的 URL 总是说当我使用 GET 时重定向是自动的,但是文件总是返回大小为 0,如果我将 URL 粘贴到浏览器中工作正常

这是我的日志:

2021-08-11 16:40:54.217 DEBUG 2149 --- [  restartedMain] o.s.web.client.RestTemplate              : HTTP GET <<Myurl.....>>
2021-08-11 16:40:54.697 DEBUG 2149 --- [  restartedMain] o.s.web.client.RestTemplate              : Response 302 FOUND
2021-08-11 16:59:14.609 DEBUG 2149 --- [  restartedMain] b.c.l.b.api.BalcaoonlineApiApplication   : File Size: 0

如果我使用这样的公共文件(https://www.mds.gov.br/webarquivos/public/NOBSUAS_2012.pdf)在谷歌中找到,下载工作正常..我使用来自 Baeldung 网站的示例:https ://www.baeldung.com/spring-resttemplate-download-large-file#download-without-resume

标签: spring-boot

解决方案


推荐阅读