Android |《看完不忘系列》之Retrofit

嗨,我是哈利迪~《看完不忘系列》将以从树干到细枝的思路分析一些技术框架,本文将对开源项目Retrofit进行介绍。

本文约2800字,阅读大约8分钟。

Retrofit源码基于最新版本2.9.0

预备

Retrofit使得网络调用可以像RESTful设计风格一样简洁,如:

1
2
3
4
5
interface WanApi {
//用注解标记网络请求方式get、post,参数path、query等
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);
}

又如,后端的Spring Boot框架通过约定大于配置思想省去了很多配置,其在网络接口RestController上也运用了这种风格,

1
2
3
4
5
6
7
8
9
10
11
@RestController
public class ActivityController {
@Autowired
private ActivityService activityService;

//用注解标记网络请求方式和入参
@GetMapping("/goods")
public ResultEntity queryGoods(@RequestParam("page") int page) {
return activityService.queryGoods(page);
}
}

Retrofit的底层网络实现基于okhttp,自身的类不是很多,最核心的点就是动态代理了。代理模式简单来说,就是为对象提供一个增强控制其访问的代理。下面我们先来了解下静态代理动态代理~

静态代理

编译期就完成代理

  • 源码级:手动编写代理类、APT生成代理类
  • 字节码级:编译期生成字节码、

举个栗子,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
interface 赚钱 {
void makeMoney(int income);
}

class 小鲜肉 implements 赚钱 { //委托类
@Override
public void makeMoney(int income) {
System.out.println("开拍,赚个" + income);
}
}

class 经纪人 implements 赚钱 { //代理类
赚钱 xxr;

public 经纪人(赚钱 xxr) {
this.xxr = xxr;
}

@Override
public void makeMoney(int income) {
if (income < 1000_0000) { //控制访问
System.out.println("才" + income + ",先回去等通知吧");
} else {
xxr.makeMoney(income);
}
}
}

public static void main(String[] args) {
赚钱 xxr = new 小鲜肉();
赚钱 jjr = new 经纪人(xxr);
jjr.makeMoney(100_0000); //输出:才1000000,先回去等通知吧
jjr.makeMoney(1000_0000); //输出:开拍,赚个10000000
}

为什么代理类委托类要实现相同接口?是为了尽可能保证代理类的内部结构和委托类一致,这样对代理类的操作都可以转移到委托类上,代理类只关注增强控制

动态代理

运行期生成字节码,如Proxy.newProxyInstance、CGLIB

Proxy.newProxyInstance是java自带,只能对接口代理(因为生成的类已经继承了Proxy,java没法多继承)

CGLIB则更强大,还能对普通类代理,底层基于ASM(ASM使用类似SAX解析器逐行扫描来提高性能)

举个栗子,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class 合作标准 implements InvocationHandler {
赚钱 xxr;

public 合作标准(赚钱 xxr) {
this.xxr = xxr;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
int income = (int) args[0];
if (income < 1000_0000) { //控制访问
System.out.println("才" + income + ",先回去等通知吧");
return null;
} else {
return method.invoke(xxr, args);
}
}
}

public static void main(String[] args) {
赚钱 xxr = new 小鲜肉();
合作标准 standard = new 合作标准(xxr);
//生成类(字节码):class $Proxy0 extends Proxy implements 赚钱
//然后反射创建其实例bd,即来一场临时的商务拓展
赚钱 bd = (赚钱) Proxy.newProxyInstance(赚钱.class.getClassLoader(),
new Class[]{赚钱.class},
standard);
//调用makeMoney,内部转发给了合作标准的invoke
bd.makeMoney(100_0000);
bd.makeMoney(1000_0000);
}

通过栗子可以看出,动态代理不需要提前创建具体的代理类(如经纪人经纪公司)去实现赚钱接口,而是先拟一份合作标准(InvocationHandler),等到运行期才创建代理类$Proxy0(字节码),然后反射创建其实例商务拓展,这样显得更为灵活。

了解完动态代理,就可以开始Retrofit之旅了~

树干

简单使用

引入依赖,

1
2
3
4
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'

定义接口WanApi

1
2
3
4
5
interface WanApi {
//用注解标记网络请求类型get,参数path
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);
}

发起请求,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class RetrofitActivity extends AppCompatActivity {
final String SERVER = "https://www.xxx.com/";

@Override
protected void onCreate(Bundle savedInstanceState) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER) //指定服务器地址
.addConverterFactory(GsonConverterFactory.create()) //用gson将数据反序列化成实体
.build();
//运行期生成一个实现WanApi接口的类(字节码),并反射创建其实例
WanApi wanApi = retrofit.create(WanApi.class);
//得到Retrofit的call,他封装了okhttp的call
Call<WanArticleBean> call = wanApi.articleList(0);
//请求入队
call.enqueue(new Callback<WanArticleBean>() {
@Override
public void onResponse(Call<WanArticleBean> call, Response<WanArticleBean> response) {
//得到数据实体
WanArticleBean bean = response.body();
//不同于okhttp,Retrofit已经用Handler帮我们切回主线程了
mBinding.tvResult.setText("" + bean.getData().getDatas().size());
}

@Override
public void onFailure(Call<WanArticleBean> call, Throwable t) {}
});
}
}

实现原理

由于Retrofit底层基于okhttp,哈迪在《看完不忘系列》之okhttp已经对网络流程做了分析,所以本文忽略网络实现只关注Retrofit自身的一些处理,Retrofit对象的构建就是简单的builder模式,我们直接看create,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Retrofit.java
public <T> T create(final Class<T> service) {
//验证
validateServiceInterface(service);
return (T)
//动态代理
Proxy.newProxyInstance(
service.getClassLoader(), //类加载器
new Class<?>[] {service}, //一组接口
new InvocationHandler() {
//判断android和jvm平台及其版本
private final Platform platform = Platform.get();

@Override
public Object invoke(Object proxy, Method method, Object[] args){
//如果该方法是Object的方法,直接执行不用管
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//isDefaultMethod:检查是否是java8开始支持的接口默认方法
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(method).invoke(args); //我们关注这里
}
});
}

Proxy.newProxyInstance动态代理,运行期会生成一个类(字节码)如$ProxyN,实现传入的接口即WanApi,重写接口方法然后转发给InvocationHandler的invoke,如下(伪代码),

1
2
3
4
5
6
class $ProxyN extends Proxy implements WanApi{
Call<WanArticleBean> articleList(@Path("page") int page){
//转发给invocationHandler
invocationHandler.invoke(this,method,args);
}
}

我们先看validateServiceInterface验证逻辑,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Retrofit.java
private void validateServiceInterface(Class<?> service) {
//检查:WanApi不是接口就抛异常...
//检查:WanApi不能有泛型参数,不能实现其他接口...
if (validateEagerly) { //是否进行严格检查,默认关闭
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) { //遍历WanApi方法
//不是默认方法,并且不是静态方法
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
//把方法提前加载进来(检查下有没有问题)
loadServiceMethod(method);
}
}
}
}

如果开了validateEagerly,会一次性把接口WanApi的所有方法都检查一遍并加载进来,可以在debug模式下开启,提前发现错误写法,比如在@GET请求设置了@Body这种错误就会抛出异常:

java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.

loadServiceMethod

然后是loadServiceMethod(method).invoke(args),看名字可知是先找方法,然后执行,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Retrofit.java
//缓存,用了线程安全ConcurrentHashMap
final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

ServiceMethod<?> loadServiceMethod(Method method) {
ServiceMethod<?> result = serviceMethodCache.get(method);
//WanApi的articleList方法已缓存,直接返回
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//解析articleList的注解,创建ServiceMethod并缓存起来
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}

跟进ServiceMethod.parseAnnotations,

1
2
3
4
5
6
7
8
//ServiceMethod.java
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
//1.
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//检查:articleList方法返回类型不能用通配符和void...
//2.
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}

先看1. RequestFactory.parseAnnotations,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//RequestFactory.java
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}

class Builder {
RequestFactory build() {
//解析方法注解如GET
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//省略各种检查...
//解析参数注解如Path
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
parameterHandlers[p] =
parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}
//省略各种检查...
return new RequestFactory(this);
}
}

得到RequestFactory后,看2. HttpServiceMethod.parseAnnotations,HttpServiceMethod负责适配和转换处理,将接口方法的调用调整为HTTP调用,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//HttpServiceMethod.java
//ResponseT响应类型如WanArticleBean,ReturnT返回类型如Call
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
//省略kotlin协程逻辑...
Annotation[] annotations = method.getAnnotations();
//遍历找到合适的适配器
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
//得到响应类型,如WanArticleBean
Type responseType = callAdapter.responseType();
//遍历找到合适的转换器
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
}

可见最终返回了一个CallAdapted,看到CallAdapted,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//CallAdapted extends HttpServiceMethod extends ServiceMethod
class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;

CallAdapted(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}

@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
//适配器
return callAdapter.adapt(call);
}
}

那这个CallAdapter实例到底是谁呢,我们先回到Retrofit.Builder,

1
2
3
4
5
6
7
8
9
10
11
//Retrofit.Builder.java
public Retrofit build() {
Executor callbackExecutor = this.callbackExecutor;
//如果没设置线程池,则给android平台设置一个默认的MainThreadExecutor(用Handler将回调切回主线程)
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
//添加默认的DefaultCallAdapterFactory
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
}

DefaultCallAdapterFactory这个工厂创建具体的CallAdapter实例,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//DefaultCallAdapterFactory.java
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
//如果指定了SkipCallbackExecutor注解,就表示不需要切回主线程
final Executor executor =
Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
? null
: callbackExecutor;
return new CallAdapter<Object, Call<?>>() {
@Override
public Type responseType() {
return responseType;
}

@Override
public Call<Object> adapt(Call<Object> call) {
//默认情况下,返回用主线程池包装的Call,他的enqueue会使用主线程池的execute
return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
}
};
}

invoke

前边loadServiceMethod得到了CallAdapted,然后执行invoke,实现在父类HttpServiceMethod里,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//HttpServiceMethod.java
final ReturnT invoke(Object[] args) {
//终于见到okhttp了!
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}

class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;

@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
//用前边得到的适配器,把OkHttpCall包成ExecutorCallbackCall
return callAdapter.adapt(call);
}
}

然后是请求入队,ExecutorCallbackCall.enqueue -> OkHttpCall.enqueue,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//ExecutorCallbackCall.java
void enqueue(final Callback<T> callback) {
delegate.enqueue(
new Callback<T>() {
@Override
public void onResponse(Call<T> call, final Response<T> response) {
//将回调切回主线程
callbackExecutor.execute(
() -> {
callback.onResponse(ExecutorCallbackCall.this, response);
});
//...
}

@Override
public void onFailure(Call<T> call, final Throwable t) {}
});
}

//OkHttpCall.java
void enqueue(final Callback<T> callback) {
//okhttp逻辑
okhttp3.Call call;
call.enqueue(new okhttp3.Callback() {
void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
callback.onResponse(OkHttpCall.this, response);
}
})
}

总算把流程跑通了,回到前边再看一遍流程图,就豁然开朗了~

细枝

CallAdapter

CallAdapter适配器用于适配返回类型,比如还可以支持Rxjava、协程的使用,

1
2
3
4
5
6
7
8
9
interface WanApi {
//Call
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);

//Rxjava,需要 addCallAdapterFactory(RxJavaCallAdapterFactory.create())
@GET("article/list/{page}/json")
Observable<WanArticleBean> articleListRx(@Path("page") int page);
}

Converter

Converter转换器用于转换参数类型,比如把Long时间戳格式化成string再传给后端,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
interface WanApi {
//Long cur 当前时间
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page, @Query("cur") Long cur);
}

class TimeConverter implements Converter<Long, String> {
private SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

@Override
public String convert(Long value) throws IOException {
if (value > 1_000_000_000_000L) {//毫秒,不是很严谨 - -
return mFormat.format(new Date(value));
}
return String.valueOf(value);
}
}

class TimeConverterFactory extends Converter.Factory {

@Override
public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (type == Long.class) {
//使用自定义TimeConverter
return new TimeConverter();
}
return super.stringConverter(type, annotations, retrofit);
}

public static Converter.Factory create() {
return new TimeConverterFactory();
}
}

//再设置一下就行了,addConverterFactory(TimeConverterFactory.create())

动态替换url

在构建Retrofit时传入HttpUrl对象,之后这个实例就一直存在不会更改,所以可以反射修改他的字段比如host,来实现动态替换服务端地址,

1
2
3
4
5
6
String SERVER = "https://www.xxx.com/";
HttpUrl httpUrl = HttpUrl.get(SERVER);
Retrofit retrofit = new Retrofit.Builder()
//.baseUrl(SERVER)
.baseUrl(httpUrl) //使用HttpUrl
.build();

尾声

咱们下期见~😆

系列文章:

参考资料


欢迎关注原创技术公众号:哈利迪ei