🧱 构建接口
在 Forest 依赖加入好之后,就可以构建 HTTP 请求的接口了。
在 Forest 中,所有的 HTTP 请求信息都要绑定到某一个接口的方法上,不需要编写具体的代码去发送请求。请求发送方通过调用事先定义好 HTTP 请求信息的接口方法,自动去执行 HTTP 发送请求的过程,其具体发送请求信息就是该方法对应绑定的 HTTP 请求信息。
# 简单请求
创建一个interface,并用@Request注解修饰接口方法。
public interface MyClient {
    @Request("http://localhost:8080/hello")
    String simpleRequest();
}
 1
2
3
4
5
6
2
3
4
5
6
通过@Request注解,将上面的MyClient接口中的simpleRequest()方法绑定了一个 HTTP 请求,
其 URL 为http://localhost:8080/hello
,并默认使用GET方式,且将请求响应的数据以String的方式返回给调用者。
# 稍复杂点的请求
public interface MyClient {
    @Request(
            url = "http://localhost:8080/hello/user",
            headers = "Accept: text/plain"
    )
    String sendRequest(@Query("uname") String username);
}
 1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
上面的sendRequest方法绑定的 HTTP 请求,定义了 URL 信息,以及把Accept:text/plain加到了请求头中,
方法的参数String username绑定了注解@Query("uname"),它的作用是将调用者传入入参 username 时,自动将username的值加入到 HTTP 的请求参数uname中。
如果调用方代码如下所示:
@Resource
MyClient myClient;
myClient.sendRequest("foo");
 1
2
3
4
2
3
4
MyClient myClient = Forest.client(MyClient.class);
myClient.sendRequest("foo");
 1
2
3
2
3
// Make sure to add code blocks to your code group
这段调用所实际产生的 HTTP 请求如下:
GET http://localhost:8080/hello/user?uname=foo
HEADER:
    Accept: text/plain
帮助我们改善此文档  (opens new window)
  上次更新: 2025/06/24, 01:16:57