本文将Retrofit注解完全解析一下,好记性不如烂笔头。
注解分类:
Retrofit注解分为三类。分别是Http请求方法注解、标记类注解和参数类注解。
Http请求方式注解8种:GET 、POST、 PUT、 DELETE、 HEAD、 PATCH、 OPTIONS 和HTTP。前7中分别代表Http的请求方法,Http则可以替换以上7中,也可以拓展请求方法。
2.标记类注解3种:FormUrlEncode、Multipart和 Streaming。
参数类注解10种:Header、Headers、Body、Path、Field、FieldMap、Part、PartMap、Query、QueryMap和URL。
Retrofit初始化:
String url = "http://102.10.10.132/api/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
GET请求:
public interface RetrofitService {
@GET("news")
Call getDate();
}
public interface RetrofitService {
@GET("news")
Call getDate(@Path("name") String name);
}
public interface RetrofitService {
@GET("news")
Call getDate(@Path("name") String name, @Path("type")String type);
}
一个或多个参数在问号之后
public interface RetrofitService {
@GET("news")
Call getDate(@Query("name") String nameStr);
}
public interface RetrofitService {
@GET("news")
Call getDate(@Query("name") String nameStr, @Query("type")String typeStr);
}
public interface RetrofitService {
@GET("news")
Call getDate(@QueryMap Map params);
}
POST请求:
public interface RetrofitService {
@FormUrlEncoded
@POST("Comment/{id}")
Call getDate(@Path("id") String CommentId, @Field("reason") String reason);
}
public interface RetrofitService {
@FormUrlEncoded
@POST("Comment/{id}")
Call getDate(@Path("id") String CommentId,@Query("token") String token, @Field("reason") String reason);
}
public interface RetrofitService {
@FormUrlEncoded
@POST("Comment/{id}")
Call getDate(@Path("id") String CommentId,@Query("token") String token, @Body T t);
}
public interface RetrofitService {
@Multipart
@POST("Comment")
Call getDate(@Part MultipartBody.Part photo,@Part("description")RequestBody description);
}
DELETE请求:
public interface RetrofitService {
@DELETE("Delete/{DeleteId}")
Call getDate(@Path("DeleteId") String CommentId);
}
public interface RetrofitService {
@DELETE("Delete/{DeleteId}")
Call getDate(@Path("DeleteId") String CommentId,@Query("token") String token);
}
public interface RetrofitService {
@HTTP(method = "DELETE",path = "Comments",hasBody = true)
Call getDate(@Body T t);
}
用自己的理解总结:
Path相当于参数替换
Field一般用于POST请求中,后面跟要提交的表单,并且添加@ FormUrlEncoded搭配使用。
Body 一般用于POST请求中,相当于多个Field,以对象的方式提交。