Retrofit2 源码分析
整体流程(以异步请求为例)
- 通过建造者模式创建 Retrofit 对象
- Retrofit 对象通过 create 方法(动态代理)创建请求接口(API)的对象
- API 对象执行具体接口方法获取 retrofit2.Call(实际指向retrofit2.OkHttpCall,也可以是定义的其他类) 对象
- retrofit2.Call 对象执行 enqueue(异步请求)方法,会调用 okhttp3.Call 的 enqueue 方法,然后又将执行结果返回
源码分析
-
创建 Retrofit 对象
public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories); callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor)); // Make a defensive copy of the converters. List<Converter.Factory> converterFactories = new ArrayList<>( 1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize()); // Add the built-in converter factory first. This prevents overriding its behavior but also // ensures correct behavior when using converters that consume all types. converterFactories.add(new BuiltInConverters()); converterFactories.addAll(this.converterFactories); converterFactories.addAll(platform.defaultConverterFactories()); return new Retrofit( callFactory, baseUrl, unmodifiableList(converterFactories), unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly); }
- baseUrl: 必须设置,不能为空,否则抛出异常
- okhttp3.Call.Factory callFactory(OkHttpClient):用于创建 okhttp3.Call,暂时用不到
- Executor callbackExecutor :用于切换到主线程,然后执行请求结果的回调
-
Platform platform:在 Android 中,指向 retrofit2.Platform#Android 类
platform = Platform.get();
private static final Platform PLATFORM = findPlatform(); static Platform get() { return PLATFORM; } private static Platform findPlatform() { return "Dalvik".equals(System.getProperty("java.vm.name")) ? new Android() // : new Platform(true); }
-
callbackExecutor:指向 retrofit2.Platform#Android#MainThreadExecutor 类
@Override public Executor defaultCallbackExecutor() { return new MainThreadExecutor(); }
-
retrofit2.Platform#Android#MainThreadExecutor:创建主线程的 Handler,来切换执行线程
static final class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable r) { handler.post(r); } }
-
List<CallAdapter.Factory> callAdapterFactories:用于 对最终返回数据进行二次处理 的 类 的 工厂类 的 集合
-
List<Converter.Factory> converterFactories:用于 将返回数据转换为用户需要的类型 的 类 的 工厂类 的 集合
-
validateEagerly:是否提前解析接口中的方法(在创建 retrofit2.Call 阶段详细分析),默认 false
-
return new Retrofit(…):返回 Retrofit 对象
-
-
创建接口对象
public <T> T create(final Class<T> service) { validateServiceInterface(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 @Nullable 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); } args = args != null ? args : emptyArgs; return platform.isDefaultMethod(method) ? platform.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(method).invoke(args); } }); }
-
创建 retrofit2.Call 对象(执行接口中具体方法时,会执行动态代理的 invoke 方法)
@Override public @Nullable 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); } args = args != null ? args : emptyArgs; return platform.isDefaultMethod(method) ? platform.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(method).invoke(args); }
- 如果是 Object 中的方法,直接执行该方法(使用反射)
if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); }
- args :表示参数
- 如果是 default 方法(Java 8,接口可以有默认实现,default 方法就是接口中的默认实现),直接执行该方法,否则,执行 loadServiceMethod(method).invoke(args)(一般都执行该方法)
platform.isDefaultMethod(method) ? platform.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(method).invoke(args);
- loadServiceMethod:通过 Method 获取 ServiceMethod 对象(本地维护一个线程安全的 hashMap 表,将创建的 ServiceMethod 放入)
ServiceMethod<?> loadServiceMethod(Method method) { ServiceMethod<?> result = serviceMethodCache.get(method); if (result != null) return result; synchronized (serviceMethodCache) { result = serviceMethodCache.get(method); if (result == null) { result = ServiceMethod.parseAnnotations(this, method); serviceMethodCache.put(method, result); } } return result; }
-
ServiceMethod.parseAnnotations(this, method):创建 ServiceMethod
abstract class ServiceMethod<T> { static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) { RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method); 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); } abstract @Nullable T invoke(Object[] args); }
-
创建 RequestFactory requestFactory :对网络请求的参数进行解析,并存储到 RequestFactory 对象中
-
对返回类型进行判断
-
创建 ServiceMethod(以非 kotlin 为例,其余类似),并返回
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations( Retrofit retrofit, Method method, RequestFactory requestFactory) { boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction; boolean continuationWantsResponse = false; boolean continuationBodyNullable = false; Annotation[] annotations = method.getAnnotations(); Type adapterType; if (isKotlinSuspendFunction) { ... } else { adapterType = method.getGenericReturnType(); } CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method, adapterType, annotations); Type responseType = callAdapter.responseType(); if (responseType == okhttp3.Response.class) { throw methodError( method, "'" + getRawType(responseType).getName() + "' is not a valid response body type. Did you mean ResponseBody?"); } if (responseType == Response.class) { throw methodError(method, "Response must include generic type (e.g., Response<String>)"); } // TODO support Unit for Kotlin? if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) { throw methodError(method, "HEAD method must use Void as response type."); } Converter<ResponseBody, ResponseT> responseConverter = createResponseConverter(retrofit, method, responseType); okhttp3.Call.Factory callFactory = retrofit.callFactory; if (!isKotlinSuspendFunction) { return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter); } else if (continuationWantsResponse) { ... } else { ... } }
-
Type adapterType = method.getGenericReturnType(); 获取方法返回的数据类型
-
CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method, adapterType, annotations); 在 Retrofit 对象的 callAdapterFactories 列表中找到适配数据类型是 adapterType 的对象,默认是 DefaultCallAdapterFactory,CallAdapter 对象是 ExecutorCallbackCall
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter( Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) { try { //noinspection unchecked return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw methodError(method, e, "Unable to create call adapter for %s", returnType); } }
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) { return nextCallAdapter(null, returnType, annotations); } public CallAdapter<?, ?> nextCallAdapter( @Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) { Objects.requireNonNull(returnType, "returnType == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = callAdapterFactories.indexOf(skipPast) + 1; for (int i = start, count = callAdapterFactories.size(); i < count; i++) { CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this); if (adapter != null) { return adapter; } } ... }
-
Converter<ResponseBody, ResponseT> responseConverter = createResponseConverter(retrofit, method, responseType); 在 Retrofit 对象的 converterFactories 列表中,找到将 ResponseBody 类型转换为 用户需要类型的对象
private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter( Retrofit retrofit, Method method, Type responseType) { Annotation[] annotations = method.getAnnotations(); try { return retrofit.responseBodyConverter(responseType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw methodError(method, e, "Unable to create converter for %s", responseType); } }
public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) { return nextResponseBodyConverter(null, type, annotations); } public <T> Converter<ResponseBody, T> nextResponseBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = converterFactories.indexOf(skipPast) + 1; for (int i = start, count = converterFactories.size(); i < count; i++) { Converter<ResponseBody, ?> converter = converterFactories.get(i).responseBodyConverter(type, annotations, this); if (converter != null) { //noinspection unchecked return (Converter<ResponseBody, T>) converter; } } ... }
-
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter); 创建并返回 ServiceMethod 对象,实际指向 retrofit2.HttpServiceMethod#CallAdapted 类
-
-
-
ServiceMethod.invoke:首先执行 HttpServiceMethod 的 invoke 方法,然后执行 CallAdapted 的 adapt 方法
@Override final @Nullable ReturnT invoke(Object[] args) { Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter); return adapt(call, args); }
@Override protected ReturnT adapt(Call<ResponseT> call, Object[] args) { return callAdapter.adapt(call); }
-
callAdapter 默认为 DefaultCallAdapterFactory 执行 get 方法后的对象,执行 adapt 方法后,返回 Call 对象,实际指向 ExecutorCallbackCall
final class DefaultCallAdapterFactory extends CallAdapter.Factory { ... @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { ... return new CallAdapter<Object, Call<?>>() { @Override public Type responseType() { return responseType; } @Override public Call<Object> adapt(Call<Object> call) { return executor == null ? call : new ExecutorCallbackCall<>(executor, call); } }; }
-
-
- loadServiceMethod:通过 Method 获取 ServiceMethod 对象(本地维护一个线程安全的 hashMap 表,将创建的 ServiceMethod 放入)
- 如果是 Object 中的方法,直接执行该方法(使用反射)
-
执行数据请求(调用 ExecutorCallbackCall 的 enqueue 方法,delegate 为 OkHttpCall)
@Override public void enqueue(final Callback<T> callback) { Objects.requireNonNull(callback, "callback == null"); delegate.enqueue( new Callback<T>() { @Override public void onResponse(Call<T> call, final Response<T> response) { callbackExecutor.execute( () -> { if (delegate.isCanceled()) { // Emulate OkHttp's behavior of throwing/delivering an IOException on // cancellation. callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled")); } else { callback.onResponse(ExecutorCallbackCall.this, response); } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(() -> callback.onFailure(ExecutorCallbackCall.this, t)); } }); }
总结
-
创建 Retrofit 对象
-
创建接口对象
-
执行接口方法,获得 retrofit2.Call 对象
- loadServiceMethod
- ServiceMethod.parseAnnotations
- HttpServiceMethod.parseAnnotations
- return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter)
- requestFactory :对接口方法解析后,保存参数的类
- callFactory :okhttp3.Call.Factory
- responseConverter:可以将 ResponseBody (okhttp 原始数据)转换为用户需要类型的 Converter
- callAdapter:可以转换为接口方法返回类型的 callAdapter
- ServiceMethod.invoke
- HttpServiceMethod.invoke
- CallAdapted.adapt
- callAdapter.adapt
- loadServiceMethod
-
执行数据请求
- retrofit2.Call 对象发起数据请求,调用 retrofit2.OkHttpCall,继续调用 okhttp3.Call