简单请求

新建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(@Query("uname") String username);
  7. }

上面的sendRequest方法绑定的 HTTP 请求,定义了 URL 信息,以及把Accept:text/plain加到了请求头中, 方法的参数String username绑定了注解@Query(“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