🌠 响应对象
# 响应对象
响应对象是 Forest 中最核心组件之一,其类名为ForestResponse
其主要承担的作用是,将服务端返回的响应信息(包括响应头、响应体、请求异常信息)封装在该对象中
并提供直观的API对返回的数据进行读取
# 获取响应对象
如同《请求对象》一样,在 Forest 中有两种获取 ForestResponse 对象的方法:声明式接口方法返回响应对象和编程式接口创建响应对象。
# 声明式
public interface MyClient {
/**
* Get类型请求,url路径为 /test
* <p>ForestResponse是带泛型参数的类型
* <p>泛型参数代表返回的响应数据所期望转化成的类型
*
* @return Forest响应对象
*/
@Get("/test")
ForestResponse<String> getForestResponse();
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
调用 getForestResponse()
方法后即可马上发送请求,并且获取该请求所返回的 Forest 响应对象
@Resource
MyClient myClient;
... ...
// 发送请求,并获取从服务端返回的响应数据对象
ForestResponse<String> response = myClient.getForestResponse();
// 获取响应结果数据
String result = response.getResult();
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 编程式
ForestResponse response = Forest.get("/test")
.execute(ForestResponse.class);
// 获取响应结果数据
String result = response.getResult();
1
2
3
4
2
3
4
# 未关闭的响应对象
上面这些例子所用的 ForestResponse 是普通的 Forest 响应对象,该类型对象能够自动关闭响应连接,无需调用者操心,非常方便,但坏处就是会消耗额外的性能和内存。
在某些对性能和内存资源较为苛刻的场景,如下载文件、或读取体积较大的数据,就要考虑使用手动模式的响应对象 (UnclosedResponse)。
UnclosedResponse 对象的获取方式也和 ForestResponse 对象一样,可分为声名式和编程式
# 声明式
public interface MyClient {
/**
* Get类型请求,url路径为 /test
* <p>UnclosedResponse是带泛型参数的手动响应类型
* <p>泛型参数代表返回的响应数据所期望转化成的类型
*
* @return Forest响应对象
*/
@Get("/test")
UnclosedResponse<String> getUnclosedResponse();
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
调用 getForestResponse()
方法后即可马上发送请求,并且获取该请求所返回的 Forest 响应对象
@Resource
MyClient myClient;
......
// 发送请求,并获取从服务端返回的未关闭响应数据对象
UnclosedResponse<String> response = myClient.getUnclosedResponse();
// 关闭连接
response.close();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 编程式
UnclosedResponse response = Forest.get("/test")
.executeAsUnclosedResponse();
// 关闭连接
response.close();
1
2
3
4
2
3
4
或者
UnclosedResponse response = Forest.get("/test")
.execute(UnclosedResponse.class);
// 关闭连接
response.close();
1
2
3
4
2
3
4
# 关闭方式
# 调用 close()
最简单直接的方式是调用 UnclosedResponse 对象的close()
方法。
// 关闭连接
response.close();
1
2
2
但非常不推荐这样做。
# 使用 try-with-resources
除了调用close()
,更好更安全的办法是使用try-with-resources
语法自动关闭响应
// 使用 try-with-resources 托管 UnclosedResponse 对象
try (UnclosedResponse response = Forest.get("/").executeAsUnclosedResponse()) {
//...
}
// try 代码块结束后会自动关闭 response
1
2
3
4
5
2
3
4
5
# 开启流后自动关闭
UnclosedResponse 虽然是未关闭的响应,但有些时候也不需要我们手动关闭。
使用openStream()
读取完流之后,会自动关闭连接。
Forest.get("/")
.executeAsUnclosedResponse()
.openStream((in, res) -> {
// in 为 InputStream 对象
// res 为 UnclosedResponse 响应对象
});
// openStream 完成后会自动关闭连接
1
2
3
4
5
6
7
2
3
4
5
6
7
# 读取数据后自动关闭
使用readAsString()
、getResult()
、get(Class)
等方法读取完数据后,也会自动关闭连接
// 使用 readAsString() 将响应数据作为字符串读取完后,就会自动关闭
Forest.get("/")
.executeAsUnclosedResponse()
.readAsString();
// 调用完 getResult() 读取发序列化后结果,就会自动关闭连接
Forest.get("/")
.executeAsUnclosedResponse()
.getResult();
// 调用 get(Class) 按任意类型进行读取后,也会自动关闭连接
Forest.get("/")
.executeAsUnclosedResponse()
.get(MyData.class);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
帮助我们改善此文档 (opens new window)
上次更新: 2025/06/24, 01:16:57