Retrofit用法详解

来源:互联网 发布:淘宝腔调 编辑:程序博客网 时间:2024/05/22 21:04

一、基础介绍

1、定义Java形式的HTTP API接口

public interface BlueService {   @GET("book/search")   Call<BookSearchResponse> getSearchBooks(@Query("q") String name,         @Query("tag") String tag, @Query("start") int start,         @Query("count") int count);}

2、实现GitHubService接口

Retrofit retrofit = new Retrofit.Builder()   .baseUrl("https://api.douban.com/v2/")   .addConverterFactory(GsonConverterFactory.create())   .build();BlueService service = retrofit.create(BlueService.class);

3、请求

Call<BookSearchResponse> call = mBlueService.getSearchBooks("小王子", "", 0, 3);
  • 同步请求
BookSearchResponse response = call.execute().body();
  • 异步请求
call.enqueue(new Callback<BookSearchResponse>() {    @Override    public void onResponse(Call<BookSearchResponse> call, Response<BookSearchResponse> response){        asyncText.setText("异步请求结果: " + response.body().books.get(0).altTitle);    }    @Override    public void onFailure(Call<BookSearchResponse> call, Throwable t) {    }});

二、引入相关包

compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

三、注解

Retrofit 共22个注解,根据功能大概分为三类:

  • 请求方法类
  • 标记类
  • 参数类

1、请求方法类

序号 名称 1 GET 2 POST 3 PUT 4 DELETE 5 PATCH 6 HEAD 7 OPTIONS 8 HTTP


  • 序号 1 ~ 7

    分别对应 HTTP 的请求方法;
    接收一个字符串表示接口 path ,与 baseUrl 组成完整的 Url;
    可以不指定,结合 @Url 注解使用;
    url 中可以使用变量,如 {id} ,并使用 @Path(“id”) 注解为 {id} 提供值。

举个例子

public interface BlogService{    @GET("blog/{id}")    Call<ResponseBody> getBlog(@Path("id") int id);}
  • 序号 8

    可用于替代以上 7 个,及其他扩展方法;
    有 3 个属性:method、path、hasBody、

举个例子

public interface BlogService{    /**    * Cmethod  请求方法,不区分大小写    * path    路径    * hasBody 是否有请求体    */    @HTTP(method = "get", path = "blog/{id}", hasBody = false)    Call<ResponseBody> getBlog(@Path("id") int id);}

2、标记类

分类 名称 备注 表单请求 FormUrlEncoded 请求体是 From 表单 ~~ Multipart 请求体是支持文件上传的 From 表单 标记 Streaming 响应体的数据用流的形式返回


  • FormUrlEncoded
    登录页面使用:Content-Type:application/x-www-form-urlencoded

  • Multipart
    上传文件使用:Content-Type:multipart/form-data

//传单个文件@Multipart@POST("v1/create")Call<ResponseBody> create(@Part("pictureName") RequestBody pictureName,  @Part MultipartBody.Part pictureRequestBody pictureNameBody = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), "pictureName");File picture= new File(path);RequestBody requestFile = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), picture);// MultipartBody.Part is used to send also the actual file nameMultipartBody.Part picturePart = MultipartBody.Part.createFormData("picture", picture.getName(), requestFile);//调接口create(pictureNameBody, picturePart);//传多个文件@Multipart@POST("v1/create")Call<ResponseBody> create(@Part("pictureName") RequestBody pictureName,   @PartMap Map<String, RequestBodyRequestBody pictureNameBody = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), "pictureName");File picture= new File(path);RequestBody requestFile = RequestBody.create(MediaType.parse(AppConstants.CONTENT_TYPE_FILE), picture);Map<String, RequestBody> params = new HashMap<>();params.put("picture\"; filename=\"" + picture.getName() + "", requestFile);//调接口create(pictureNameBody, params);
  • Streaming
    作用于方法,当返回的数据较大时,需要使用该注解。

3、参数类

分类 名称 备注 作用于方法 Headers 添加请求头 作用于方法参数(形参) Header 添加不固定的 Header ~~ Body 非表单请求体 ~~ Field 表单字段,与 FieldMap、FormUrlEncoded 配合 ~~ FieldMap 表单字段,与 Field、FormUrlEncoded 配合;接受 Map<String, String> 类型,非 String 类型会调用 toString() 方法 ~~ Part 表单字段,与 PartMap 配合,适合文件上传情况 ~~ PartMap 表单字段,与 Part 配合,适合文件上传情况;默认接受 Map<String, RequestBody> 类型,非 RequestBody 会通过 Converter 转换 ~~ Path 用于URL ~~ Query 用于URL ~~ QueryMap 用于URL ~~ Url 用于URL


注意:

1、Map 用来组合复杂的参数;

2、Query、QueryMap 与 Field、FieldMap 功能一样,生成的数据形式一样;
Query、QueryMap 的数据体现在 Url 上;
Field、FieldMap 的数据是请求体;

3、{占位符}和 PATH 尽量只用在URL的 path 部分,url 中的参数使用 Query、QueryMap 代替,保证接口的简洁;

4、Query、Field、Part 支持数组和实现了 Iterable 接口的类型, 如 List、Set等,方便向后台传递数组,示例如下:

Call<ResponseBody> foo(@Query("ids[]") List<Integer> ids);// 结果// ids[]=0&ids[]=1&ids=2
  • Headers
    使用 @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("users/{username}")Call<User> getUser(@Path("username") String username);
  • Header
    使用 @Header 注解动态更新请求头,匹配的参数必须提供给 @Header ,若参数值为 null ,这个头会被省略,否则,会使用参数值的 toString 方法的返回值。
@GET("user")Call<User> getUser(@Header("Authorization") String authorization)
  • Body
    使用 @Body 注解,指定一个对象作为 request body 。
@POST("users/new")Call<User> createUser(@Body User user);

对象会被 Retrofit 实例中指定的转换器转换,若未添加转换器,只能使用 RequestBody ,如下:

@POST("users/new")Call<RequestBody> createUser(@Body User user);--------------------------------------------------------------@Headers({"Content-type:application/json;charset=UTF-8"})@POST("/api/v1/trade/HasAccount.json")Call<BaseResponse> createCommit(@Body RequestBody route);    Gson gson=new Gson();    HashMap<String,String> paramsMap=newHashMap<>();    paramsMap.put("userId","173");    String strEntity = gson.toJson(paramsMap);    body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);    Call<BaseResponse> call = api.getService().createCommit(body);
  • Field
    表单提交,如登录
 @FormUrlEncoded @POST("v1/login") Call<ResponseBody> userLogin(@Field("phone") String phone, @Field("password") String password);
  • FieldMap
@FormUrlEncoded@POST("book/reviews")Call<String> addReviews(@FieldMap Map<String, String> fields);
  • Part
public interface FileUploadService {      // 上传单个文件    @Multipart    @POST("upload")    Call<ResponseBody> uploadFile(            @Part("description") RequestBody description,            @Part MultipartBody.Part file);    // 上传多个文件    @Multipart    @POST("upload")    Call<ResponseBody> uploadMultipleFiles(            @Part("description") RequestBody description,            @Part MultipartBody.Part file1,            @Part MultipartBody.Part file2);}
  • PartMap
    @Multipart    @POST("cyxx/Feedback/add.do")    Observable<ResponseBody> getFeedbackResult(            @PartMap Map<String, RequestBody> params    );
  • Path
    请求 URL 可以替换模块来动态改变,替换模块是 {}包含的字母数字字符串,替换的参数必须使用 @Path 注解的相同字符串。
// 链接 http://baseurl/blog/idpublic interface BlogService{    @GET("blog/{id}")    Call<ResponseBody> getBlog(@Path("id") int id);}
  • Query
    查询参数
// 链接 http://baseurl/blog/id?sort=ShortStrpublic interface BlogService{    @GET("blog/{id}")    Call<ResponseBody> getBlog(@Path("id") int id, @Query("sort") String sort);}//传数组public interface BlogService{    @GET("blog/{id}")    Call<ResponseBody> getBlog(@Path("id") int id, @Query("linked[]") String... linked);}
  • QueryMap
    复杂的查询参数
// 链接 http://baseurl/blog/id?param1=Param1&param2=Param2...public interface BlogService{    @GET("blog/{id}")    Call<ResponseBody> getBlog(@Path("id") int id, @QueryMap Map<String, String> options);}
  • Url
    动态URL设置
    使用Retrofit2一般都是针对于 一一 baseURL,其它接口都是拼接不同的参数,如get/photo,search?name=xiaohong&&sex=female,这样的形式。
    但是一些请求此时又要访问不同的url只能重新生成一个Retrofit2实例,实质上还有一种形式去处理,就是使用@url注解。
public interface UserService {      @GET    public Call<ResponseBody> profilePicture(@Url String url);}

上面的@url 可以接收https://s3.amazon.com/profile-picture/path,使用如下

Retrofit retrofit = Retrofit.Builder()      .baseUrl("https://your.api.url/");    .build();UserService service = retrofit.create(UserService.class);  service.profilePicture("https://s3.amazon.com/profile-picture/path");// request url results in:// https://s3.amazon.com/profile-picture/path

参考:
1、http://www.jianshu.com/p/bf884248cb37
2、http://blog.csdn.net/ysmintor_/article/details/70271680
3、http://blog.csdn.net/fanatic_/article/details/53066938
4、http://blog.csdn.net/itachi85/article/details/53007262
5、http://www.jianshu.com/p/308f3c54abdd
6、http://square.github.io/retrofit/
7、http://blog.csdn.net/duanyy1990/article/details/52139294
8、http://www.jianshu.com/p/32bfd5fd8b48