不知道你们在工做中有没有碰到过在代码级别中进行上传和下载呢,通常的场景为调用第三方的接口进行上传大文件和下载大文件。html
我一个小伙伴最近在工做中就碰到了,他须要在代码中调用第三方http接口进行原始文件的上传,而后须要调用第三方接口把第三方服务处理好的数据文件下载到本地。他说其实没什么技术难度,百度了下,代码示例也不少,httpclient就支持上传文件和下载,就是代码写的太多了,不怎么优雅。java
他给我看了httpclient的上传代码:git
String uploadUrl = "http://xxxxx.com/upload"; HttpPost httpPost = new HttpPost(uploadUrl); FileBody fileBody = new FileBody(new File("C:/Users/Administrator/Desktop/source.excel")); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("file",fileBody); // 设置其余参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new NameValuePair("Accept","application/json, text/plain, */*")); nvps.add(new NameValuePair("Accept-Encoding","gzip, deflate, br")); nvps.add(new NameValuePair("Accept-Language","zh-CN,zh;q=0.9")); nvps.add(new NameValuePair("Connection","keep-alive")); nvps.add(new NameValuePair("Content-Length","28700")); nvps.add(new NameValuePair("Content-Type","multipart/form-data; boundary=----WebKitFormBoundarypaEfQmIQBbUrkI0c")); nvps.add(new NameValuePair("Host","xxxxx.com")); nvps.add(new NameValuePair("Origin","http://xxxxx.com")); nvps.add(new NameValuePair("Referer","xxxxx.com/admin/goods_edit.html")); nvps.add(new NameValuePair("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36")); HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity(reqEntity); try { CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println("上传以后返回的状态码:"+response.getStatusLine().getStatusCode()); try { HttpEntity resEntity = response.getEntity(); respStr = getRespString(resEntity); EntityUtils.consume(reqEntity); } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } } catch (IOException e) { e.printStackTrace(); } System.out.println("resp=" + respStr);
由于要从代码里进行上传远端,须要创建一个MultipartEntityBuilder,设置各类header,小伙伴问我有什么框架能够提供更加优雅的写法。spring
其实不少框架都有更加简洁的API,可是我仍是推荐给了他最近一款比较火的框架:Forest
json
这个框架我之前也有写文推荐过:一款直击痛点的优秀http框架,让我超高效率完成了和第三方接口的对接segmentfault
Forest
是一款主要致力于http请求各个场景的工具框架,基本上几行代码就能够解决几乎大部分的http的场景,api主打易用性,提供了不少特性,符合国内开发者的习惯,并且做者更新也比较勤快。目前的稳定release版本可用于生产环境。api
项目主页地址:https://gitee.com/dt_flys/forest数组
Forest
能解决大部分http场景中的问题,对于上传下载,做者在最新的版本中提供了上传下载功能,可以以最简单的方式实现,极大程度方便了开发者。springboot
对于想了解Forest
其余功能的童鞋,能够去项目主页或者我以前写的文章了解下。这里仅介绍用Forest
上传和下载的新特性。app
这里以springboot项目为例,依赖Forest
:
<dependency> <groupId>com.dtflys.forest</groupId> <artifactId>spring-boot-starter-forest</artifactId> <version>1.4.6</version> </dependency>
定义RemoteDataHander
接口:
public interface RemoteDataHander{ @Post(url = "http://xxxxx.com/upload") void upload(@DataFile("file") File file, OnProgress onProgress); @Get(url = "http://xxxxx.com/report/xxx.zip") @DownloadFile(dir = "${0}") void downloadFile(String dir, OnProgress onProgress); }
这个接口会被Forest
扫描组件在启动时扫描到并注册进spring容器,而后就能够像使用本地方法同样去调用进行上传和下载操做了。
参数中声明的OnProgress
参数,是一个接口,你能够去实现它去完成进度的回调:
File file = myClient.downloadFile("D:\\TestDownload", progress -> { System.out.println("total bytes: " + progress.getTotalBytes()); // 文件大小 System.out.println("current bytes: " + progress.getCurrentBytes()); // 已下载字节数 System.out.println("progress: " + Math.round(progress.getRate() * 100) + "%"); // 已下载百分比 if (progress.isDone()) { // 是否下载完成 System.out.println("-------- Download Completed! --------"); } });
上传和下载均可以去实现OnProgress
的,固然你也能够不传。
除了上述例子的用法,Forest
也支持其余类型的文件参数和返回参数,如文件流,字节数组,MultipartFile类型等等。用法以下:
上传:
/** * File类型对象 */ @Post(url = "http://xxxxx.com/upload") Map upload(@DataFile("file") File file, OnProgress onProgress); /** * byte数组 * 使用byte数组和Inputstream对象时必定要定义fileName属性 */ @Post(url = "http://xxxxx.com/upload") Map upload(@DataFile(value = "file", fileName = "${1}") byte[] bytes, String filename); /** * Inputstream 对象 * 使用byte数组和Inputstream对象时必定要定义fileName属性 */ @Post(url = "http://xxxxx.com/upload") Map upload(@DataFile(value = "file", fileName = "${1}") InputStream in, String filename); /** * Spring Web MVC 中的 MultipartFile 对象 */ @PostRequest(url = "http://xxxxx.com/upload") Map upload(@DataFile(value = "file") MultipartFile multipartFile, OnProgress onProgress); /** * Spring 的 Resource 对象 */ @Post(url = "http://xxxxx.com/upload") Map upload(@DataFile(value = "file") Resource resource);
下载:
/** * 返回类型用byte[],可将下载的文件转换成字节数组 */ @GetRequest(url = "http://localhost:8080/images/test-img.jpg") byte[] downloadImageToByteArray(); /** * 返回类型用InputStream,用流的方式读取文件内容 */ @Request(url = "http://localhost:8080/images/test-img.jpg") InputStream downloadImageToInputStream();
其中下载返回的字节数组和输入流,能够用于自定义操做
从使用者角度去出发,Forest
给了一个很是友好的api,并且声明和配置都很是简单。极大程度的方便了开发者。不光上传下载场景,在其余经常使用的http的调用场景中,Forest
也面面俱到,是一个http层面一站式解决式工具。有兴趣的同窗能够去看看,必定会提升你http场景的开发效率。
我也曾和做者探讨过当下http领域的一些框架以及Forest
的发展路线。做者比较谦虚,回答了我一些问题
做者一直都表示,但愿把各类http的场景作到极致,使开发者真正能用几行代码就能优雅的实现复杂的http的场景,作开源项目不易,为这种工匠精神点赞。但愿forest之后能为更多开发者在工做中解决痛点。
我是铂赛东,一个认真温暖且执着的男生,我坚持作原创的技术科技分享号,关注「元人部落」,我每周会出一篇实用的原创技术文章,陪着你一块儿走,再也不惧怕。