✨ 执行请求
ForestRequest 对象可以直接调用 execute()
方法执行请求,即发送请求到远端服务器
// 发送 Get 请求, url: http://localhost/
Forest.get("/").execute();
// execute 方法会返回服务端响应的数据
Object ret = Forest.post("/").execute();
1
2
3
4
2
3
4
Forest请求对象也提供多个方法,以满足用不同类型接受数据的需要
# 自定义类型
execute(Class<R> clazz)
执行请求发送过程
- 参数
clazz
: 结果返回类型, Class 对象
// 以字符串方式接受数据
String str = Forest.get("/").execute(String.class);
// 以自定义类型方式接受数据
MyResult result = Forest.get("/").execute(MyResult.class);
1
2
3
4
2
3
4
# Type类型
execute(Type type)
执行请求发送过程
- 参数
type
: 结果返回类型, Type 接口实例
// 使用 TypeReference 工具类包裹泛型类型
TypeReference<List<String>> typeRef = new TypeReference<List<String>>() {};
// 获取 Type 对象
Type type = typeRef.getType();
// 以自定义Type类型形式接受数据
List<String> strList = Forest.get("/").execute(type);
1
2
3
4
5
6
2
3
4
5
6
注意
new TypeReference
实例化的时候一定要带上泛型参数,否则无效
# 泛型类型
execute(TypeReference typeReference)
执行请求发送过程
- 参数
typeReference
: 结果返回类型的引用, Type 接口实例
// 使用 TypeReference 工具类包裹泛型类型
TypeReference<List<String>> typeRef = new TypeReference<List<String>>() {};
// 以带复杂泛型参数的类型形式接受数据
List<String> strList = Forest.get("/").execute(typeRef);
1
2
3
4
2
3
4
注意
new TypeReference
实例化的时候一定要带上泛型参数,否则无效TypeReference
是com.dtflys.forest.utils
包下的类,不要引用到其它库中的同名类型
# 字符串类型
executeAsString()
执行请求发送过程,并获取字符串类型结果
- 返回值 : 字符串类型数据
// 直接以 String 类型接受数据
String str = Forest.get("/").executeAsString();
1
2
2
# 列表类型
executeAsList()
执行请求发送过程,并获取List类型结果
- 返回值 : 列表对象
// 直接以 List 类型接受数据
List<String> list = Forest.get("/").executeAsList();
1
2
2
# Map类型
executeAsMap()
执行请求发送过程,并获取Map类型结果
- 返回值 : Map 对象
// 直接以 Map 类型接受数据
Map<String, String> map = Forest.get("/").executeAsMap();
1
2
2
# 响应类型
# 自动关闭的响应类型
ForestResponse 作为返回的响应类型,它在请求完成之后会自动完全连接,无需调用者操心。
获取不带泛型的 Forest 响应对象
// executeAsResponse 方法返回响应对象
ForestResponse response = Forest.get("/").executeAsResponse();
// 之后无需手动关闭响应
1
2
3
2
3
或者
// 直接以响应类型接受数据
ForestResponse response = Forest.get("/").execute(ForestResponse.class);
// 之后无需手动关闭响应
1
2
3
2
3
获取带泛型的自动关闭的响应对象
// 直接以响应类型接受数据, 并带有泛型参数类型
ForestResponse<List<MyUser>> resposne = Forest.get("/").execute(
new TypeReference<ForestResponse<List<MyUser>>>() {});
// 之后无需手动关闭响应
1
2
3
4
2
3
4
# 手动关闭的响应类型
orestResponse 作为能自动关闭请求连接的响应对象,使用起来非常方便,不容易出错。但有些时候,为了考虑获得更好的性能,或减少内存消耗,就不得不使用需要手动关闭的响应类型 UnclosedResponse。
// executeAsUnclosedResponse 方法返回未关闭的响应对象 (需要手动关闭)
UnclosedResponse response = Forest.get("/").executeAsUnclosedResponse();
// ...
// 需要手动关闭
response.close();
1
2
3
4
5
2
3
4
5
或者
// 直接以响应类型接受数据
ForestResponse response = Forest.get("/").execute(UnclosedResponse.class);
// ...
// 需要手动关闭
response.close();
1
2
3
4
5
2
3
4
5
获取带泛型的未关闭响应对象
// 直接以响应类型接受数据, 并带有泛型参数类型
ForestResponse<List<MyUser>> resposne = Forest.get("/").execute(
new TypeReference<ForestResponse<List<MyUser>>>() {});
// ...
// 需要手动关闭
response.close();
1
2
3
4
5
6
2
3
4
5
6
帮助我们改善此文档 (opens new window)
上次更新: 2025/06/24, 01:16:57