背景
最近被安排了一个活,纯体力的重复性工作,将开发一个项目的指定资源通过现有的下载接口下载下来。
思路
因为没有提供批量下载接口,同时下载的资源需要自己筛选,想着这样人工处理特别麻烦,个人也没有什么进步,就想着写一段代码处理,这样处理起来准确,效率高,后续有类似的任务还可以将这段代码改改后继续使用。
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 { //url string 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
出现这种报错是必须指定的具体的文件,而不是文件夹,同时尽量保证存放文件的文件夹必须存在
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论