Android中Retrofit常见注解全解析

1、什么是Retrofit?

Retrofit 是一个Square开发的安卓客户端请求库。其中内部封装了okhttp库。官方的介绍是使用非常简短 Retrofit使用注解,能够极大的简化网络请求数据的代码。

Retrofit常用注解包括:@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url

2、@Query,@QueryMap

@Query主要用于Get请求数据,用于拼接在拼接在Url路径后面的查询参数,一个@Query相当于拼接一个参数,多个参数中间用,隔开。

使用示例代码:

Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://ms.csdn.net/") .build();public interface csdnService { //如果没有参数 @GET("api/ask/all_questions") Call<List<Repo>> getData(); //只有少数参数 @GET("api/ask/all_questions") Call<List<Repo>> getData(@Query("page") int page, @Query("is_reward") int is_reward);}

@QueryMap:主要的效果等同于多个@Query参数拼接,主要也用于Get请求网络数据。

@GET("http://ms.csdn.net/api/ask/all_questions")Call<List<Repo>> getData(@QueryMap Map<String,String> params);Map<String,String> params=new HashMap();params.put("name","liming");params.put("age",24);params.put("sex","man");params.put("city","Shanghai");

这样等价于请求数据接口为

http://ms.csdn.net/api/ask/all_questions?name=liming&age=24&sex=man&city=Shanghai

3、@Field,@FieldMap

@Field的用法类似于@Query,就不在重复列举了,主要不同的是@Field主要用于Post请求数据。

@FieldMap的用法类似于@QueryMap。

两者主要区别是:如果请求为post实现,那么最好传递参数时使用@Field、@FieldMap和@FormUrlEncoded。因为@Query和或QueryMap都是将参数拼接在url后面的,而@Field或@FieldMap传递的参数时放在请求体的。

4、@FormUrlEncoded

我们在代码中使用是不是发现了@POST比起@GET多了一个@FromUrlEncoded的注解。

如果去掉@FromUrlEncoded在post请求中使用@Field和@FieldMap,那么程序会抛出Java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. 的错误异常。

所以如果平时公司如果是Post请求的话,千万别忘记了加这@FromUrlEncoded注解。

@FormUrlEncoded@POST("users/user/question")Call<TnGou> getTngouPost(@Field("page") int page);

5、@Path

@Path主要用于Get请求,用于替换Url路径中的变量字符。

publicinterface csdnService {@GET("users/{user}/question") Call<List<Repo>> getData(@Path("user") String user); }

该接口定义了一个getData方法,该方法通过GET请求去访问服务器的users/{user}/question路径,其中通过@Path注解会把路径中的{user}替换成参数user的具体值。比如:user的值如果是zhangsan,那么Url的路径就是users/zhangsan/question.

6、@Url

@Url是动态的Url请求数据的注解。需要注意的是使用@Path时,path对应的路径不能包含”/”,不然每个加到host Url后面的东西都会被省略掉。千万注意了

Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://ms.csdn.net/") .build(); public interface csdnService {@GET Call<List<Repo>> getData(@Url String user); }

猜你喜欢

转载自blog.csdn.net/tanghongchang123/article/details/79916020