Android app开发中Retrofit框架的初步上手使用

2019-12-10 19:05:41王振洲

 先看@GET

/** Make a GET request to a REST path relative to base URL. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
@RestMethod("GET")
public @interface GET {
 String value();
}


 

@GET本身也被几个Anotation注解,@Target表示@GET注解是用于方法的,value方法就返回这个注解的value值,在上例中就是/group/{id}/users,然后就是@RestMethod

@Documented
@Target(ANNOTATION_TYPE)
@Retention(RUNTIME)
public @interface RestMethod {
 String value();
 boolean hasBody() default false;
}

RestMethod是一个用于Annotation的Annotation,比如上面的例子中用来注解的@GET,value方法就返回GET,hasBody表示是否有Body,对于POST这个方法就返回true

@Documented
@Target(METHOD)
@Retention(RUNTIME)
@RestMethod(value = "POST", hasBody = true)
public @interface POST {
 String value();
}


 

Retrofit的Annotation包含请求方法相关的@GET、@POST、@HEAD、@PUT、@DELETA、@PATCH,和参数相关的@Path、@Field、@Multipart等。

定义了Annotation要就有解析它的方法,在Retrofit中解析的位置就是RestMethodInfo,但在这之前需要先看哪里使用了RestMethodInfo,前面说了Retrofit使用了动态代理生成了我们定义的接口的实现类,而这个实现类是通过RestAdapter.create返回的,所以使用动态代理的位置就是RestAdapter,接下来就看一下RestAdapter。