⚽ 回调函数
在Forest中的回调函数使用单方法的接口定义,这样可以使您在 Java 8 或 Kotlin 语言中方便使用 Lambda 表达式。
# 成功/失败回调函数
在接口方法加入OnSuccess<T>类型或OnError类型的参数
@Request(
        url = "http://localhost:8080/hello/user",
        headers = {"Accept:text/plain"},
        data = "username=${username}"
)
String send(@Var("username") String username, OnSuccess<String> onSuccess, OnError onError);
 1
2
3
4
5
6
2
3
4
5
6
如这两个回调函数的类名所示的含义一样,OnSuccess<T>在请求成功调用响应时会被调用,而OnError在失败或出现错误的时候被调用。
其中OnSuccess<T>的泛型参数T定义为请求响应返回结果的数据类型。
myClient.send("foo", (String resText, ForestRequest request, ForestResponse response) -> {
        // 成功响应回调
        System.out.println(resText);    
    },
    (ForestRuntimeException ex, ForestRequest request, ForestResponse response) -> {
        // 异常回调
        System.out.println(ex.getMessage());
    });
 1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
提示
- 在异步请求中只能通过OnSuccess<T>回调函数接或Future返回值接受数据。
 - 而在同步请求中,OnSuccess<T>回调函数和任何类型的返回值都能接受到请求响应的数据。
 - OnError回调函数可以用于异常处理,一般在同步请求中使用try-catch也能达到同样的效果。
 
# 下载进度回调函数
在接口方法加入OnProgress类型的参数
/**
 * OnProgress 回调函数可以用于下载文件类请求方法的参数中
 */
@Get("/xxx-img.jpg")
byte[] downloadFile(OnProgress onProgress);
 1
2
3
4
5
2
3
4
5
如果请求成功访问到URL指定的文件资源,且开始进行下载,则会反复调用参数中传入的 OnProgress 回调函数
// 每传输一定的字节数,便会调用一次 OnProgress 回调函数
byte[] bytes = downloadClient.downloadFile(progress -> {
    System.out.println("------------------------------------------");
    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!   --------");
        atomicProgress.set(progress);
    }
});
 1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 重定向回调函数
当前请求响应接受到的是 302、304 等状态码时,Forest 会触发自动重定向,即会立刻发送一个新的请求
若要拦截或修改新的跳转请求可以使用 OnRedirection 回调函数
/**
 * OnRedirection 回调函数可以用自动重定向请求方法的参数中
 */
@Post("/")
String testRedirect(OnRedirection onRedirection);
 1
2
3
4
5
2
3
4
5
当触发重定向时,在发送新的跳转请求前,会调用参数中传入的 OnRedirection 回调函数
String result = redirectClient.testNotAutoRedirect(((redirectReq, prevReq, prevRes) -> {
    // prevReq 为跳转前的请求对象
    // prevRes 为跳转前接受到的响应对象
    // redirectReq 为新的即将跳转的请求对象
}));
 1
2
3
4
5
2
3
4
5
帮助我们改善此文档  (opens new window)
  上次更新: 2024/12/26, 12:59:11