HTTP调用API框架Forest

Forest是一个高层的、极简的声明式HTTP调用API框架
相比于直接使用Httpclient您不再用写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求

maven

<dependency>
    <groupId>com.dtflys.forest</groupId>
    <artifactId>forest-spring-boot-starter</artifactId>
    <version>1.5.36</version>
</dependency>

application.yaml / application.properties中配置的 HTTP 基本参数 

forest:
  max-connections: 1000        # 连接池最大连接数
  connect-timeout: 3000        # 连接超时时间,单位为毫秒
  read-timeout: 3000           # 数据读取超时时间,单位为毫秒

扫描接口,在Springboot的配置类或者启动类上加上@ForestScan注解,并在basePackages属性里填上远程接口的所在的包名

@SpringBootApplication

@Configuration

@ForestScan(basePackages = "com.yoursite.client")

public class MyApp { }

 使用方式,创建一个interface,用@Get注解修饰之。

import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Retry;
import com.dtflys.forest.annotation.Var;
public interface MyClient {

    @Get("http://localhost:8080/hello")
    String helloForest();


    /**
     * 用户中心登录
     *
     * @param req
     * @return
     */
    @Post(url = "{url}/api/v1/login/autoLoginOnlyByAuthCode"
            , contentType = "application/json"
            , connectTimeout = 2000
            , readTimeout = 2000)
    @Retry(maxRetryCount = "1", maxRetryInterval = "100")
    String login(@Var("url") String url, @JSONBody AutoLoginOnlyByAuthCodeReq req);
}

发送请求 

@Component
public class MyService {
    
    // 注入自定义的 Forest 接口实例
    @Resource
    private MyClient myClient;

    public void testClient() {
        // 调用自定义的 Forest 接口方法
        // 等价于发送 HTTP 请求,请求地址和参数即为 helloForest 方法上注解所标识的内容
        String result = myClient.helloForest();
        // result 即为 HTTP 请求响应后返回的字符串类型数据
        System.out.println(result);
    }

}

参考🎯 Spring环境使用 | Forest

相关推荐

  1. HTTP调用API框架Forest

    2024-05-10 09:36:03       14 阅读
  2. 量子计算编程框架Forest

    2024-05-10 09:36:03       12 阅读
  3. 调用第三方接口:springBoot整合forest

    2024-05-10 09:36:03       26 阅读
  4. Go HTTP 调用(下)

    2024-05-10 09:36:03       38 阅读
  5. Go HTTP 调用(上)

    2024-05-10 09:36:03       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-10 09:36:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-10 09:36:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-10 09:36:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-10 09:36:03       20 阅读

热门阅读

  1. MongoDB 从部署到掌握

    2024-05-10 09:36:03       14 阅读
  2. MongoDB聚合运算符:$toObjectId

    2024-05-10 09:36:03       13 阅读
  3. React 学习-4

    2024-05-10 09:36:03       11 阅读
  4. iOS-SSL固定证书

    2024-05-10 09:36:03       9 阅读
  5. 快速了解Vuex

    2024-05-10 09:36:03       9 阅读
  6. Vue3:视图渲染

    2024-05-10 09:36:03       8 阅读
  7. VMware 的三种网络模式

    2024-05-10 09:36:03       10 阅读
  8. flutter 在onError函数中不推荐使用“runZoned

    2024-05-10 09:36:03       9 阅读
  9. rust学习(openssl rsa加解密文件)

    2024-05-10 09:36:03       11 阅读