Forest,这款轻量级 HTTP 客户端 API 框架很强( 八 )


/** * File类型对象 */@Post(url = "/upload")Map upload(@DataFile("file") File file, OnProgress onProgress);/** * byte数组 * 使用byte数组和Inputstream对象时一定要定义fileName属性 */@Post(url = "/upload")Map upload(@DataFile(value = https://www.isolves.com/it/cxkf/kj/2022-10-27/"file", fileName = "${1}") byte[] bytes, String filename);/** * Inputstream 对象 * 使用byte数组和Inputstream对象时一定要定义fileName属性 */@Post(url = "/upload")Map upload(@DataFile(value = "file", fileName = "${1}") InputStream in, String filename);/** * Spring Web MVC 中的 MultipartFile 对象 */@PostRequest(url = "/upload")Map upload(@DataFile(value = "file") MultipartFile multipartFile, OnProgress onProgress);/** * Spring 的 Resource 对象 */@Post(url = "/upload")Map upload(@DataFile(value = "file") Resource resource);(2)多文件批量上传
/** * 上传Map包装的文件列表 * 其中 ${_key} 代表Map中每一次迭代中的键值 */@PostRequest(url = "/upload")ForestRequest<Map> uploadByteArrayMap(@DataFile(value = https://www.isolves.com/it/cxkf/kj/2022-10-27/"file", fileName = "${_key}") Map byteArrayMap);/** * 上传List包装的文件列表 * 其中 ${_index} 代表每次迭代List的循环计数(从零开始计) */@PostRequest(url = "/upload")ForestRequest uploadByteArrayList(@DataFile(value = "file", fileName = "test-img-${_index}.jpg") List byteArrayList);/** * 上传数组包装的文件列表 * 其中 ${_index} 代表每次迭代List的循环计数(从零开始计) */@PostRequest(url = "/upload")ForestRequest uploadByteArrayArray(@DataFile(value = "file", fileName = "test-img-${_index}.jpg") byte[][] byteArrayArray);(3)下载
/** * 在方法上加上@DownloadFile注解 * dir属性表示文件下载到哪个目录 * filename属性表示文件下载成功后以什么名字保存,如果不填,这默认从URL中取得文件名 * OnProgress参数为监听上传进度的回调函数 */@Get(url = "http://localhost:8080/images/xxx.jpg")@DownloadFile(dir = "${0}", filename = "${1}")File downloadFile(String dir, String filename, OnProgress 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!--------");}});如果您不想将文件下载到硬盘上,而是直接在内存中读取,可以去掉@DownloadFile注解,并且用以下几种方式定义接口:
/** * 返回类型用byte[],可将下载的文件转换成字节数组 */@GetRequest(url = "http://localhost:8080/images/test-img.jpg")byte[] downloadImageToByteArray();/** * 返回类型用InputStream,用流的方式读取文件内容 */@GetRequest(url = "http://localhost:8080/images/test-img.jpg")InputStream downloadImageToInputStream();4.2.5 其它使用Cookie、使用代理、自定义注解、模板表达式······
本文档部分内容摘自官方文档,具体详情可参见:Forest官网:http://forest.dtflyx.com/
注:

笔者写了一个基于Springboot的demo(Maven项目),分别采用Forest、HttpClient、Okhttp三种方式调用高德地图API,Forest中还包括拦截器的使用、下载图片等示例,项目具体目录结构如下图所示,包括Forest、HttpClient、Okhttp三部分:

Forest,这款轻量级 HTTP 客户端 API 框架很强

文章插图
 

Forest,这款轻量级 HTTP 客户端 API 框架很强

文章插图
 
使用Postman进行测试:
Forest,这款轻量级 HTTP 客户端 API 框架很强

文章插图
 


推荐阅读