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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今朝花落悲颜色

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值