快捷搜索: 王者荣耀 脱发

Forest声明式HTTP客户端框架漫谈

Forest 是一款声明式的 Java 开源 HTTP 框架,相比它的前辈 Httpclient 和 OkHttp 更简明易懂、也更容易维护,使用过程中非常丝滑故想分享给更多的朋友,此处我们进行简单的介绍和使用说明。

一. 什么是Forest

Forest为声明式HTTP客户端框架。将繁复的 HTTP 请求细节封装成 Java 接口 + 注解的形式,不必关心请求发送的具体过程。

普通HTTP请求,例使用hutool的HttpUtil:

import cn.hutool.http.HttpUtil;

String resule = HttpUtil.get("http://ditu.amap.com/service/regeo?longitude={lng}&latitude={lat}");

Forest示例:

public interface MyClient {
          
   
    @Get("http://localhost:8080/hello")
    String helloForest();
}


@Autowired
private MyClient client;

public void execute(){
          
   
    client.helloForest();
}

二. 使用Forest

  1. 引入依赖(maven) <dependency> <groupId>com.dtflys.forest</groupId> <artifactId>forest-spring-boot-starter</artifactId> <version>1.5.31</version> </dependency>
  2. Forest配置 Forest是基于约定大于配置的理念进行设计的,如果已经添加好了forest-spring-boot-starter依赖,基本上可以什么都不配置。但是也可以做一些简单的配置,具体可以参考: forest: max-connections: 1000 # 连接池最大连接数 connect-timeout: 3000 # 连接超时时间,单位为毫秒 read-timeout: 3000 # 数据读取超时时间,单位为毫秒
  3. 定义接口 public interface MyClient { /** * 测试forest的get请求 * @param param1 参数1 * @param param2 参数2 * @return */ @Get("http://localhost:8080/testGetForest?param1={param1}&param2={param2}") JSONObject getData(String param1, String param2); /** * 测试forest的post请求 * @param data body传参 * @return */ @Post("http://localhost:8080/testPostForest") JSONObject postData(@JSONBody JSONObject data); }
  4. 实际调用 @Service public class MyService{ @Autowired private MyClient client; public void run(){ client.getData("param1", "param2"); client.postData(new JSONObject()); } }

三. 总结

使用Forest极大的提高了便利性,也能够使得代码更容易维护。如果我们使用了IDEA,那么还可以搭配官方插件ForextX进行使用。

参考资料:

经验分享 程序员 微信小程序 职场和发展