Retrofit请求参数注解字段说明

来源:互联网 发布:科比场均数据每年 编辑:程序博客网 时间:2024/06/05 10:27

@Query、@QueryMap

用于Http Get请求传递参数.如:

@GET("group/users")Call<List<User>> groupList(@Query("id") int groupId);等同于:@GET("group/users?id=groupId")即将@Query的key-value添加到url后面组成get方式的参数,@QueryMap同理

@Field

用于Post方式传递参数,需要在请求接口方法上添加@FormUrlEncoded,即以表单的方式传递参数.示例:

@FormUrlEncoded@POST("user/edit")Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

@Body

用于Post,根据转换方式将实例对象转化为对应字符串传递参数.比如Retrofit添加GsonConverterFactory则是将body转化为gson字符串进行传递.

converter有如下:Gson: com.squareup.retrofit2:converter-gson Jackson: com.squareup.retrofit2:converter-jackson Moshi: com.squareup.retrofit2:converter-moshi Protobuf: com.squareup.retrofit2:converter-protobuf Wire: com.squareup.retrofit2:converter-wire Simple XML: com.squareup.retrofit2:converter-simplexml

@Path

用于URL上占位符.如:

@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId);将groupId变量的值替换到url上的id位置

@Part

配合@Multipart使用,一般用于文件上传,看官方文档示例:

@Multipart@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

header:@Header

添加http header

@GET("user")Call<User> getUser(@Header("Authorization") String authorization)等同于:@Headers("Authorization: authorization")//这里authorization就是上面方法里传进来变量的值@GET("widget/list")Call<User> getUser()

@Headers

跟@Header作用一样,只是使用方式不一样,@Header是作为请求方法的参数传入,@Headers是以固定方式直接添加到请求方法上.示例:

@Headers("Cache-Control: max-age=640000")@GET("widget/list")Call<List<Widget>> widgetList();多个设置:@Headers({    "Accept: application/vnd.github.v3.full+json",    "User-Agent: Retrofit-Sample-App"})@GET("widget/list")Call<List<Widget>> widgetList();

原文地址链接