HttpClient高级方法之Forest

一. 什么是Forest

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

管网地址:📐 Springboot环境配置 | Forest

二. 使用Forest

1.引入maven依赖

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

2.application-dev.yml中配置参数

forest:
  variables:
    url: https://gateway.com/mdm
    appId: appid
    appsecret: 11111
    accessKey: 222222

3.MyClient 配置远程接口的方式



@BaseRequest(
        baseURL = "${supplierUrl}", //yml中配置的域名
        headers = {
                "appId: ${appId}",  //yml中配置的appId
                "appsecret: ${appsecret}", //yml中配置的appId
                "Content-Type: application/json", //传参类型为json
                "sign: ${sign}",  //签名,使用方法参数@var灵活获取
                "timestamp: ${timestamp}" // //时间戳
        }
)
public interface MyClient {
    /**
     * 获取供应商列表
     *
     * @param timestamp    时间戳
     * @param sign         签名
     * @param name         供应商名称
     * @param organization 供应商组织编码
     * @return
     */
    @Post(url = "/supplier/api/query")  //需要调用的远程方法名称
    @Retry(maxRetryCount = "1", maxRetryInterval = "500") //连接数配置,间隔请求时间
    String getSupplierList(@Var("timestamp") Long timestamp, //@var注解是为了上面${}中调用
                           @Var("sign") String sign,
                           @Body("name") String name,
                           @Body("organization") String organization);
}

4.本地获取远程资源


@Slf4j
@RestController
public class SupplierController {

    @Autowired
    private MyClient myClient;

    @Value("${forest.variables.appsecret}")
    private String appsecret;
    @Value("${forest.variables.appId}")
    private String appid;

    @ApiOperation("供应商列表")
    @PostMapping(value = UrlRuleConstants.LIST_QUERY, produces = UrlRuleConstants.PRODUCES)
    public R getSupplierList(@RequestBody SupplierReq req) {
        String code = "0011";
        Long timestamp = System.currentTimeMillis();
        String name = "";
        String sign = "";
        String data = myClient.getSupplierList(timestamp, sign, name, code);
        SupplierRes res = JSONUtil.toBean(data, SupplierRes.class);
        return R.success(res);
    }

5.JSON转对象


import lombok.Data;

import java.util.List;

@Data
public class SupplierRes {

    private String code;
    private String msg;
    private boolean success;
    private List<Results> data;

    @Data
    public class Results {
        private String viewUniqueId; //数据id,用来查询明细
        private String participantCode;//客商编码
        private String participantName;//客商名称
        private String socialCreditCode;统一社会信用码
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值