欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > SpringBoot 使用RestTemplate通过http请求讲文件下载到本地

SpringBoot 使用RestTemplate通过http请求讲文件下载到本地

2025/9/16 12:02:30 来源:https://blog.csdn.net/lijiabin417/article/details/139413595  浏览:    关键词:SpringBoot 使用RestTemplate通过http请求讲文件下载到本地

背景

最近被安排了一个活,纯体力的重复性工作,将开发一个项目的指定资源通过现有的下载接口下载下来。

思路

因为没有提供批量下载接口,同时下载的资源需要自己筛选,想着这样人工处理特别麻烦,个人也没有什么进步,就想着写一段代码处理,这样处理起来准确,效率高,后续有类似的任务还可以将这段代码改改后继续使用。

1.筛选
筛选出需要的下载文件的id,这个可以根据业务调整,不一定是id,具体的实现根据业务逻辑实现;

2.下载
下载方式有两种,一种是通过postman或者apifox这种工具,通过提前构建参数和提供写有参数的文件,批量出发请求,这种只是大致想到的可以不靠编码实现的方式;另外一种是借助后端代码发起http请求,将下载的资源写入本地文件中。下面简单介绍第二种,需要时可以批量下载文件。

实现方式

资源下载方法

public static void downloadFile(String url, HttpHeaders headers, RequestParams requestParams, String outputPath) throws IOException {// 创建请求实体HttpEntity<RequestParams> entity = new HttpEntity<>(requestParams, headers);// 初始化RestTemplate,也可以自己构建配置类。final RestTemplate restTemplate = new RestTemplate();// 请求配置ResponseEntity<Resource> response = restTemplate.exchange(URI.create(url),HttpMethod.POST,entity,Resource.class);// 请求成功校验if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {// 获取资源Resource resource = response.getBody();// 确保目录存在File outputFile = new File(outputPath);File parentDir = outputFile.getParentFile();// 文件存在校验if (parentDir != null && !parentDir.exists()) {if (!parentDir.mkdirs()) {throw new IOException("Failed to create directory: " + parentDir);}}//获取流try (InputStream inputStream = resource.getInputStream();OutputStream outputStream = Files.newOutputStream(outputFile.toPath())) {StreamUtils.copy(inputStream, outputStream);}} else {throw new IOException("Failed to download file: " + response.getStatusCode());}}

实体类(可以自己定义)

@Data
public class RequestParams implements Serializable {private Long id;
}

函数调用

    public static void downloadPerPaper(PaperInfo paperInfos) throws IOException {//urlString url="https://xxxx.com";//请求头HttpHeaders headers = new HttpHeaders();headers.set("xxx","xxxxx");//请求参数final RequestParams requestParams = new RequestParams();requestParams.setId(1L);//存在存放地址String path="xx/xx/xx.doc";//调用下载方法downloadFile(url,headers,requestParams,path);}

异常处理

Exception in thread "main" java.nio.file.AccessDeniedException: xx/xx/xx

出现这种报错是必须指定的具体的文件,而不是文件夹,同时尽量保证存放文件的文件夹必须存在

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词