看Retrofit源码的一点记录

本文详细分析了Retrofit网络请求库的源码,揭示了其Builder构造函数中对不同返回类型的处理,包括CallAdapter和Converter的使用,以及默认支持的返回类型如Call和CompletableFuture。

前言

网络请求库,A type-safe HTTP client for Android and Java.
使用方法参照官方文档
本篇文章想通过分析源码看一下api接口中都支持哪些返回类型。


源码

  1. Retrofit.Builder
//建造者模式
public Retrofit build() {
      //传入的baseUrl
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }

      //传入的OkHttpClient
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
  
      //传入的callbackExecutor
      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      //保护性拷贝adapters,最后加入默认的callAdapterFactories。
      List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
      callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

      //保护性拷贝converterFactories
      List<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);
    }
  1. 动态代理
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

在这里插入图片描述

  1. 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生成ServiceMethod
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

  abstract @Nullable T invoke(Object[] args);
}
  1. HttpServiceMethod

    abstract class HttpServiceMethod<ResponseT, ReturnT> extends ServiceMethod<ReturnT> {
      
      static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
        Retrofit retrofit, Method method, RequestFactory requestFactory) {
        //前面代码省略,根据条件创建不同的ServiceMethod
        if (!isKotlinSuspendFunction) {
          //如果不是挂起函数就创建CallAdapted,使用callAdapter
          return 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);
    }
    
  2. 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);
      }
    }
    
  3. 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)
          }
        })
      }
    }
    
  4. 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

  1. CallAdapter.Factory

     abstract class Factory {
        /**
         * 通过动态代理的method返回类型来返回一个CallAdapter,如果factory不能处理则返回null
         */
        public abstract @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
            Retrofit retrofit);
    
        /**
         * 通过index和type取出泛型参数的上届通配符。
         * 例如:Map<String, ? extends Runnable>,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);
        }
      }
    
  2. 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
  3. CallAdapter(适配器模式)

    public interface CallAdapter<R, T> {
      /**
       * 返回的对象类型
       */
      Type responseType();
    
      /**
       * 返回的对象
       */
      T adapt(Call<R> call);
    }
    

Converter

  1. Converter.Factory

    abstract class Factory {
        /**
         * 返回一个converter用于转换HTTP ResponseBody到type类型,如果不能处理则返回null。
         * 例如从Call<SimpleResponse>转换为类型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<String, ? extends Runnable>,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);
        }
      }
    
  2. BuiltInConverters:请求时RequestBody转为RequestBody,响应时ResponseBody转为Void,Unit,ResponseBody。

  3. OptionalConverterFactory:api>=24时会通过defaultConverterFactories加入,响应时会创建OptionalConverter,将ResponseBody转为Optional

  4. Converter

    /**
     * 对象和HTTP中代表的含义相互转换,通过Converter.Factory创建。
     * Request创建Converter<T, RequestBody>,Response创建Converter<ResponseBody, T>
     */
    public interface Converter<F, T> {
      @Nullable T convert(F value) throws IOException;
    }
    
  5. 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();
      }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值