简单请求
新建interface,使用@Request注解修饰方法:
public interface MyClient {@Request("http://localhost:8080/hello")String simpleRequest();}
通过@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);}
上面的sendRequest方法绑定的 HTTP 请求,定义了 URL 信息,以及把Accept:text/plain加到了请求头中, 方法的参数String username绑定了注解@Query(“uname”),它的作用是将调用者传入入参 username 时,自动将username的值加入到 HTTP 的请求参数uname中。
如果调用方代码如下所示:
MyClient myClient;...myClient.sendRequest("foo");
这段调用所实际产生的 HTTP 请求如下:
GET http://localhost:8080/hello/user?uname=fooHEADER:Accept: text/plain
