Android Retrofit 2.5.0 源码分析

主要参考文章:
Android Retrofit 2.0 的详细 使用攻略(含实例讲解)
Android:手把手带你 深入读懂 Retrofit 2.0 源码

主要过程:
1、建造者模式- 初始化所需 变量
2、使用retrofit.create(AccessApi.class) 生成动态代理对象,调用方法时,解析方法上的 注解+参数+参数的注解 生成ServiceMethod 并缓存
3、ServiceMethod 中能获取到retrofit初始化的变量,ServiceMethod.invoke(...) 中使用 这些变量发起请求callAdapter.adapt(new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
4、以rxjava为例,ServiceMethod.invoke(...) 返回来Observable, 订阅者->callAdapter->OkHttpCall->okhttp3.Call->网络请求->okhttp3.Call->OkHttpCall->converter数据解析->callAdapter->订阅者

1、初始化

主要是初始化以下 Retrofit 变量

变量 说明
callFactory OkHttpClient 调用newCall(...) 生成 原始请求
CallbackExecutor MainThreadExecutor使用handler切换到主线程
CallAdapterFactories 对OkHttpCall在一次包装,可以理解为CallAdapter(OkHttpCall(okhttp3.Call))
ConverterFactories 在OkHttpCall中 对 返回的原始数据进行 解析
HttpLoggingInterceptor loggerInterceptor = new HttpLoggingInterceptor();//打印 信息
loggerInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(loggerInterceptor).build();
// 初始化Retrofit
mRetrofit = new Retrofit.Builder()
    .client(client)
    .baseUrl(baseUrl)
    .addConverterFactory(GsonConverterFactory.create(buildGson()))
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build();

1.1 Retrofit.Builder() 变量

private final Platform platform; //平台类型
private @Nullable okhttp3.Call.Factory callFactory;//OkHttpClient

private @Nullable HttpUrl baseUrl;
//自己添加的 GsonConverterFactory
private final List converterFactories = new ArrayList<>();
//自己添加的 RxJava2CallAdapterFactory
private final List callAdapterFactories = new ArrayList<>();
//没赋值 就是用 platform.defaultCallbackExecutor() = MainThreadExecutor
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;

平台类型 有 Android, java8;这里主要看android

平台类型 CallbackExecutor CallAdapterFactories ConverterFactories
Android MainThreadExecutor CompletableFutureCallAdapterFactory
(api 24以上才有)
ExecutorCallAdapterFactory
OptionalConverterFactory
(api 24以上才有)
java8 。。。 。。。 。。。

1.2 Retrofit.Builder.build() 得到Retrofit 实例

Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
List converterFactories, List callAdapterFactories,
@Nullable Executor callbackExecutor, boolean validateEagerly) {

  this.callFactory = callFactory;//OkHttpClient
  this.baseUrl = baseUrl;
  this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
  //BuiltInConverters + 自己添加的 + android平台 
  //BuiltInConverters、GsonConverterFactory、 OptionalConverterFactory(api24以上有)
  this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
  //自己添加的+android平台  RxJava2CallAdapterFactory,CompletableFutureCallAdapterFactory(>api24)、ExecutorCallAdapterFactory
  this.callbackExecutor = callbackExecutor;//android 平台来说就是 MainThreadExecutor
  this.validateEagerly = validateEagerly;//作用:是否提前对业务接口中的注解进行验证转换的标志位

}
-- CallbackExecutor CallAdapterFactories ConverterFactories
Retrofit.Builder MainThreadExecutor CompletableFutureCallAdapterFactory(>api24)
ExecutorCallAdapterFactory
OptionalConverterFactory
(>api24)
Retrofit MainThreadExecutor RxJava2CallAdapterFactory
CompletableFutureCallAdapterFactory(>api24)
ExecutorCallAdapterFactory
BuiltInConverters
GsonConverterFactory
OptionalConverterFactory
(>api24)

2、使用

构建用了动态代理, 最终是通过okhttp
2.1 ServiceMethod 构建

public class JavaBean {}
public interface AccessApi {
  @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
  Call getCall();
}
AccessApi NetService = retrofit.create(AccessApi.class);
Call call = NetService.getCall();

retrofit.create(AccessApi.class) 生成 代理对象

public  T create(final Class service) {
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
      eagerlyValidateMethods(service);//提前解析所有方法,加入缓存
    }
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service },
       new InvocationHandler() {
        private final Platform platform = Platform.get();
        private final Object[] emptyArgs = new Object[0];

        @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
        throws Throwable {//返回 接口方法的返回参数,即方法返回的结果
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
                return method.invoke(this, args);
            }
            //1.8之后接口可以有默认的实现
            if (platform.isDefaultMethod(method)) {
                return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
        }
       });
}

loadServiceMethod(…) —> ServiceMethod.parseAnnotations(this, method); 根据方法的注解 生成 ServiceMethod实例

static  ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
    RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
    //解析方法的注解,方法参数的注解,加上各种校验注解使用的正确性,构造出RequestFactory,待新建请求时使用

    Type returnType = method.getGenericReturnType();
    if (Utils.hasUnresolvableType(returnType)) {
        throw methodError(method,"Method return type must not include a type variable or wildcard: %s", returnType);
    }
    if (returnType == void.class) {
        throw methodError(method, "Service methods cannot return void.");
    }
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}

HttpServiceMethod extends ServiceMethod
返回了 new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter)

参1、requestFactory = RequestFactory.parseAnnotations(retrofit, method);
参2、callFactory = retrofit.callFactory//OkHttpClient
参3、callAdapter 从 retrofit.callAdapterFactories 中 根据返参和注解,查找并生成 合适的CallAdapter;
参4、responseConverter 从 retrofit.converterFactories中 根据返参和注解,查找并生成 合适的Converter

2.2 ServiceMethod 方法的调用

@Override ReturnT invoke(Object[] args) {
return callAdapter.adapt(
    new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}

OkHttpCall中会新建 原始请求,okhttp3 的请求

private okhttp3.Call createRawCall() throws IOException {
  okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
  if (call == null) {
    throw new NullPointerException("Call.Factory returned null.");
  }
  return call;
}

OkHttpCall.enqueue(final Callback callback) --> 调用 okhttp3.Call.enqueue(new okhttp3.Callback() {...}
结果返回后通过 responseConverter.convert(...) 将okhttp3 返回的数据 解析 为 想要的返回值(如Gson 转型)最后是一层一层回调出去。

你可能感兴趣的:(Android Retrofit 2.5.0 源码分析)