看Retrofit源码的一点记录
前言
网络请求库,A type-safe HTTP client for Android and Java.
使用方法参照官方文档。
本篇文章想通过分析源码看一下api接口中都支持哪些返回类型。
源码
- Retrofit.Builder
//建造者模式
public Retrofit build() {//传入的baseUrlif (baseUrl == null) {throw new IllegalStateException("Base URL required.");}//传入的OkHttpClientokhttp3.Call.Factory callFactory = this.callFactory;if (callFactory == null) {callFactory = new OkHttpClient();}//传入的callbackExecutorExecutor callbackExecutor = this.callbackExecutor;if (callbackExecutor == null) {callbackExecutor = platform.defaultCallbackExecutor();}//保护性拷贝adapters,最后加入默认的callAdapterFactories。List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));//保护性拷贝converterFactoriesList<Converter.Factory> converterFactories = new ArrayList<>(1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());// 先加入BuiltInConverters,最后加入默认的converterFactories。converterFactories.add(new BuiltInConverters());converterFactories.addAll(this.converterFactories);converterFactories.addAll(platform.defaultConverterFactories());return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);}
- 动态代理
public <T> T create(final Class<T> 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 @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);}if (platform.isDefaultMethod(method)) {return platform.invokeDefaultMethod(method, service, proxy, args);}return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);}});
}
ServiceMethod,Coroutines

- 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.");}//调用HttpServiceMethod的parseAnnotations生成ServiceMethodreturn HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);}abstract @Nullable T invoke(Object[] args);
}
-
HttpServiceMethod
abstract class HttpServiceMethod<ResponseT, ReturnT> extends ServiceMethod<ReturnT> {static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(Retrofit retrofit, Method method, RequestFactory requestFactory) {//前面代码省略,根据条件创建不同的ServiceMethodif (!isKotlinSuspendFunction) {//如果不是挂起函数就创建CallAdapted,使用callAdapterreturn new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);} else if (continuationWantsResponse) {//协程return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);} else {//协程return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,continuationBodyNullable);}}//前面Retrofit动态代理调用的invoke方法在这里实现@Override final @Nullable ReturnT invoke(Object[] args) {Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);return adapt(call, args);}protected abstract @Nullable ReturnT adapt(Call<ResponseT> call, Object[] args); } -
CallAdapted
final class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {//通过Call完成网络请求,再用前面传入的callAdapter将结果转换为需要的类型@Override protected ReturnT adapt(Call<ResponseT> call, Object[] args) {return callAdapter.adapt(call);} } -
SuspendForResponse,用于method是挂起函数且返回类型是Response的情况
final class SuspendForResponse<ResponseT> extends HttpServiceMethod<ResponseT, Object> {@Override protected Object adapt(Call<ResponseT> call, Object[] args) {call = callAdapter.adapt(call);//挂起函数会自动在参数列表最后加入Continuation,这时候把这个continuation取出来Continuation<Response<ResponseT>> continuation =(Continuation<Response<ResponseT>>) args[args.length - 1];// See SuspendForBody for explanation about this try/catch.try {return KotlinExtensions.awaitResponse(call, continuation);} catch (Exception e) {return KotlinExtensions.yieldAndThrow(e, continuation);}} }协程部分用到了suspendCancellableCoroutine,Call和Response是OkHttp对应类的封装,本质上还是调用call.enqueue,结果通过continuation回调返回
suspend fun <T : Any> Call<T>.awaitResponse(): Response<T> {return suspendCancellableCoroutine { continuation ->continuation.invokeOnCancellation {cancel()}enqueue(object : Callback<T> {override fun onResponse(call: Call<T>, response: Response<T>) {continuation.resume(response)}override fun onFailure(call: Call<T>, t: Throwable) {continuation.resumeWithException(t)}})} } -
SuspendForBody(部分代码),用于method是挂起函数且返回类型是ResponseT的情况,就是converter转换的对象类型
final class SuspendForBody<ResponseT> extends HttpServiceMethod<ResponseT, Object> {private final boolean isNullable;@Override protected Object adapt(Call<ResponseT> call, Object[] args) {call = callAdapter.adapt(call);//挂起函数会自动在参数列表最后加入Continuation,这时候把这个continuation取出来Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1];//分为返回类型是否可为空,KotlinExtensions.await会在返回对象为空时抛出异常try {return isNullable? KotlinExtensions.awaitNullable(call, continuation): KotlinExtensions.await(call, continuation);} catch (Exception e) {return KotlinExtensions.yieldAndThrow(e, continuation);}} }@JvmName("awaitNullable") suspend fun <T : Any> Call<T?>.await(): T? {return suspendCancellableCoroutine { continuation ->continuation.invokeOnCancellation {cancel()}enqueue(object : Callback<T?> {override fun onResponse(call: Call<T?>, response: Response<T?>) {if (response.isSuccessful) {continuation.resume(response.body())} else {continuation.resumeWithException(HttpException(response))}}override fun onFailure(call: Call<T?>, t: Throwable) {continuation.resumeWithException(t)}})} }
CallAdapter
-
CallAdapter.Factory
abstract class Factory {/*** 通过动态代理的method返回类型来返回一个CallAdapter,如果factory不能处理则返回null*/public abstract @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,Retrofit retrofit);/*** 通过index和type取出泛型参数的上届通配符。* 例如:Map,index为1时返回Runnable.*/ protected static Type getParameterUpperBound(int index, ParameterizedType type) {return Utils.getParameterUpperBound(index, type);}/*** 通过type取出原始类型。例如:List extends Runnable>返回List.class*/protected static Class<?> getRawType(Type type) {return Utils.getRawType(type);}} -
DefaultCallAdapterfFactory
- 有2种默认的CallAdapterfFactory:DefaultCallAdapterfFactory和CompletableFutureCallAdapterFactory都继承自CallAdapter.Factory
- CallAdapterfFactory的集合会先加入通过addCallAdapterFactory加入的factory,最后默认都会加入DefaultCallAdapterfFactory,Platform会判断api>=24时加入CompletableFutureCallAdapterFactory(单例饿汉)
- DefaultCallAdapterfFactory会处理method返回类型为Call的情况,ExecutorCallbackCall实现Call接口(装饰器模式)目的是call.enqueue的回调切到主线程执行(使用MainThreadExecutor切换线程)。
- CompletableFutureCallAdapterFactory会处理method返回类型为CompletableFuture的情况,T是Converter转换的类型或是Response
- 综上默认的CallAdapterfFactory支持method返回类型为Call和CompletableFuture,其余的返回类型需要传入的CallAdapterfFactory支持,如RxJava2CallAdapterFactory
-
CallAdapter(适配器模式)
public interface CallAdapter<R, T> {/*** 返回的对象类型*/Type responseType();/*** 返回的对象*/T adapt(Call<R> call); }
Converter
-
Converter.Factory
abstract class Factory {/*** 返回一个converter用于转换HTTP ResponseBody到type类型,如果不能处理则返回null。* 例如从Call转换为类型SimpleResponse。*/ public @Nullable Converter<ResponseBody, ?> responseBodyConverter(Type type,Annotation[] annotations, Retrofit retrofit) {return null;}/*** 返回一个converter用于转换type类型到HTTP RequestBody,如果不能处理则返回null。* 通常用于@Body,@Part,@PartMap注解的type。*/public @Nullable Converter<?, RequestBody> requestBodyConverter(Type type,Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {return null;}/*** 返回一个converter用于转换type类型到String,如果不能处理则返回null。* 通常用于@Field,@FieldMap,@Header,@HeaderMap,@Path,@Query,@QueryMap注解的type。 */public @Nullable Converter<?, String> stringConverter(Type type, Annotation[] annotations,Retrofit retrofit) {return null;}/*** 通过index和type取出泛型参数的上届通配符..* 例如:Map,index为1时返回Runnable.*/ protected static Type getParameterUpperBound(int index, ParameterizedType type) {return Utils.getParameterUpperBound(index, type);}/*** 通过type取出原始类型。例如:List extends Runnable>返回List.class*/protected static Class<?> getRawType(Type type) {return Utils.getRawType(type);}} -
BuiltInConverters:请求时RequestBody转为RequestBody,响应时ResponseBody转为Void,Unit,ResponseBody。
-
OptionalConverterFactory:api>=24时会通过defaultConverterFactories加入,响应时会创建OptionalConverter,将ResponseBody转为Optional
-
Converter
/*** 对象和HTTP中代表的含义相互转换,通过Converter.Factory创建。* Request创建Converter,Response创建Converter public interface Converter<F, T> {@Nullable T convert(F value) throws IOException; }*/ -
ToStringConverter会处理Object转为String的情况,优先级最低,会先到自定义的converterFactories查找,如没找到才会使用ToStringConverter。在RequestFactory的parseParameterAnnotation方法中使用,
static final class ToStringConverter implements Converter<Object, String> {static final ToStringConverter INSTANCE = new ToStringConverter();@Override public String convert(Object value) {return value.toString();} }
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
