idtitlesidebar_label
build_interface
构建接口
构建接口

在 Forest 依赖加入好之后,就可以构建 HTTP 请求的接口了。

在 Forest 中,所有的 HTTP 请求信息都要绑定到某一个接口的方法上,不需要编写具体的代码去发送请求。请求发送方通过调用事先定义好 HTTP 请求信息的接口方法,自动去执行 HTTP 发送请求的过程,其具体发送请求信息就是该方法对应绑定的 HTTP 请求信息。

简单请求

创建一个interface,并用@Request注解修饰接口方法。

  1. public interface MyClient {
  2. @Request("http://localhost:8080/hello")
  3. String simpleRequest();
  4. }

通过@Request注解,将上面的MyClient接口中的simpleRequest()方法绑定了一个 HTTP 请求, 其 URL 为http://localhost:8080/hello ,并默认使用GET方式,且将请求响应的数据以String的方式返回给调用者。

稍复杂点的请求

  1. public interface MyClient {
  2. @Request(
  3. url = "http://localhost:8080/hello/user",
  4. headers = "Accept: text/plain"
  5. )
  6. String sendRequest(@DataParam("uname") String username);
  7. }

上面的sendRequest方法绑定的 HTTP 请求,定义了 URL 信息,以及把Accept:text/plain加到了请求头中, 方法的参数String username绑定了注解@DataParam("uname"),它的作用是将调用者传入入参 username 时,自动将username的值加入到 HTTP 的请求参数uname中。

如果调用方代码如下所示:

  1. MyClient myClient;
  2. ...
  3. myClient.sendRequest("foo");

这段调用所实际产生的 HTTP 请求如下:

  1. GET http://localhost:8080/hello/user?uname=foo
  2. HEADER:
  3. Accept: text/plain