Earth Guardian

You are not LATE!You are not EARLY!

0%

Retrofit

介绍

是一个类型安全的 Http 客户端请求框架,本质是对 OkHttp 的封装

依赖

app/build.gradle 中增加依赖:

1
2
3
4
// Retrofit
compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"

基本概念

Retorift

负责配置请求过程中的基本参数,如:请求地址,结果转换器,自定义OKHttpClient 等,同时还会生成请求接口对象

Converter & Converter.Factory

分别负责网络请求结果转换以及生成Converter转换器,常见的转换器有 Gson

CallAdapter & CallAdapter.Factory

分别负责对 Retrofit.Call 实例( OkHttpCall )进行适配及生成 CallAdapter 适配器。常见适配器有: RxJava

ServiceMethod

解析接口服务所有注解、生成请求对象 Request 、解析请求结果 Response

注解关键字

RESTfull API 标准接口

@GET、@POST、@PUT、@DELETE、@HEAD

  • @GET:获取资源
  • @POST:新建资源(也可以用于更新资源)
  • @PUT:更新资源
  • @DELETE:删除资源
  • @HEAD:获取资源的元数据
1
2
@GET("text")
Single<QsbkFun> getQsbkFun(@Query("page") String index);

@HTTP

Retrofit 提供的自定义 Http 请求,可以替代标准注解

1
2
@HTTP(method = "GET", path = "text", hasBody = false)
Single<QsbkFun> getQsbkFun(@Query("page") String index);

使用流程

定义 entity,接收服务器返回数据

常见返回数据类型为 Json,这里使用 Gson 来实现数据和对象转换,如:

1
2
3
public class QsbkFun {
...
}

定义 service 接口

通过注解描述网络请求接口,返回值是 RxJava 的数据流

1
2
3
4
5
6
7
public interface QsbkFunService {
/**
* http://m2.qiushibaike.com/article/list/text?page=1
*/
@GET("text")
Single<QsbkFun> getQsbkFun(@Query("page") String index);
}

创建 Retrofit 实例

创建 Retrofit 实例,指定 Url、数据解析 Json 转换器、网络请求适配器 Rxjava 等等

离线缓存,配合 okhttp实现?

1
2
3
4
5
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();

创建 service 接口实例

并配置网络请求参数接口,并通过该接口获取数据
QsbkFunService service = retrofit.create(QsbkFunService.class);

常见错误

@GET("/") 不能为空,至少包含一个斜杠

java.lang.IllegalArgumentException: Missing either @GET URL or @Url parameter.

参考文档

  1. 官网文档
  2. 一份很详细的 Retrofit 2.0 使用教程
  3. 图解 Retrofit
  4. Retrofit分析-漂亮的解耦套路
  5. 透过Retrofit使用看其源码设计模式