🎯 Solon环境使用
在 Forest 依赖加入好,并配置好之后,就可以构建 HTTP 请求的接口了
如还没有添加好依赖或配置好,请参见《Solon环境安装》和《Solon环境配置》
在 Forest 中,所有的 HTTP 请求信息都要绑定到某一个接口的方法上,不需要编写具体的代码去发送请求。请求发送方通过调用事先定义好 HTTP 请求信息的接口方法,自动去执行 HTTP 发送请求的过程,其具体发送请求信息就是该方法对应绑定的 HTTP 请求信息
# Hello World
创建一个interface,比如命名为MyClient,并创建一个接口方法名为helloForest,同时加上@ForestClient注解。
@ForestClient
public interface MyClient {
    @Get("http://localhost:8080/hello")
    String helloForest();
}
 1
2
3
4
5
6
7
2
3
4
5
6
7
通过@Get注解,将上面的MyClient接口中的helloForest()方法绑定了一个 HTTP 请求,
其 URL 为http://localhost:8080/hello
,并默认使用GET方式,且将请求响应的数据以String的方式返回给调用者。
# 发送请求
然后便能在其他代码中从 Solon 上下文注入接口实例,然后如调用普通接口那样调用即可
@Component
public class MyService {
    
    // 注入自定义的 Forest 接口实例
    @Inject
    private MyClient myClient;
    public void testClient() {
        // 调用自定义的 Forest 接口方法
        // 等价于发送 HTTP 请求,请求地址和参数即为 helloForest 方法上注解所标识的内容
        String result = myClient.helloForest();
        // result 即为 HTTP 请求响应后返回的字符串类型数据
        System.out.println(result);
    }
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
帮助我们改善此文档  (opens new window)
  上次更新: 2024/12/26, 12:59:11