This action will force synchronization from DtFlys/forest, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
Forest是一个高层的、极简的轻量级HTTP调用API框架。
相比于直接使用Httpclient您不再用写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求。
以下例子基于Spring Boot
直接添加以下maven依赖即可
<dependency>
<groupId>com.dtflys.forest</groupId>
<artifactId>spring-boot-starter-forest</artifactId>
<version>1.4.8</version>
</dependency>
interface
就以高德地图API为栗子吧
package com.yoursite.client;
import com.dtflys.forest.annotation.Request;
import com.dtflys.forest.annotation.DataParam;
public interface AmapClient {
/**
* 聪明的你一定看出来了@Get注解代表该方法专做GET请求
* 在url中的${0}代表引用第一个参数,${1}引用第二个参数
*/
@Get(url = "http://ditu.amap.com/service/regeo?longitude=${0}&latitude=${1}")
Map getLocation(String longitude, String latitude);
}
在Spring Boot的配置类或者启动类上加上@ForestScan
注解,并在basePackages
属性里填上远程接口的所在的包名
@SpringBootApplication
@Configuration
@ForestScan(basePackages = "com.yoursite.client")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
OK,我们可以愉快地调用接口了
// 注入接口实例
@Autowired
private AmapClient amapClient;
...
// 调用接口
Map result = amapClient.getLocation("121.475078", "31.223577");
System.out.println(result);
/**
* 用@DataFile注解修饰要上传的参数对象
* OnProgress参数为监听上传进度的回调函数
*/
@Post(url = "/upload")
Map upload(@DataFile("file") String filePath, OnProgress onProgress);
可以用一个方法加Lambda同时解决文件上传和上传的进度监听
Map result = myClient.upload("D:\\TestUpload\\xxx.jpg", progress -> {
System.out.println("progress: " + Math.round(progress.getRate() * 100) + "%"); // 已上传百分比
if (progress.isDone()) { // 是否上传完成
System.out.println("-------- Upload Completed! --------");
}
});
下载文件也是同样的简单
/**
* 在方法上加上@DownloadFile注解
* dir属性表示文件下载到哪个目录
* OnProgress参数为监听上传进度的回调函数
* ${0}代表引用第一个参数
*/
@Get(url = "http://localhost:8080/images/xxx.jpg")
@DownloadFile(dir = "${0}")
File downloadFile(String dir, OnProgress onProgress);
调用下载接口以及监听下载进度的代码如下:
File file = myClient.downloadFile("D:\\TestDownload", progress -> {
System.out.println("progress: " + Math.round(progress.getRate() * 100) + "%"); // 已下载百分比
if (progress.isDone()) { // 是否下载完成
System.out.println("-------- Download Completed! --------");
}
});
亲,进群前记得先star一下哦~
扫描二维码关注公众号,点击菜单中的 进群
按钮即可进群
feat_${issue的ID号}
,如果是修改bug,则命名为fix_${issue的ID号}
。dev
分支上随新版本发布时再合到master
分支上。欢迎小伙伴们多提issue和PR,被接纳PR的小伙伴我会列在README
上的贡献者列表中:)
The MIT License (MIT)
Copyright (c) 2016 Jun Gong
Sign in for post a comment
Comment ( 0 )