Retrofit源码浅析

目录

创建Retrofit

创建代理类

创建ServiceMethod

解析注解

创建CallAdapter

创建Converter

创建Call请求

创建OkHttpCall对象

ServiceMethod的adapt方法

执行网络请求

构建网络请求

解析响应


创建Retrofit

Retrofit.Builder有以下几个成员变量,通过链式可以设置Builder的成员变量。

// 平台
private final Platform platform;
// 网络请求器
private @Nullable okhttp3.Call.Factory callFactory;
// Url
private HttpUrl baseUrl;
// Converter工厂类集合
private final List<Converter.Factory> converterFactories = new ArrayList<>();
// CallAdapter工厂类集合
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
// 回调任务调度
private @Nullable Executor callbackExecutor;

build方法创建Retrofit,将Builder的成员变量设置给Retrofit。

    public Retrofit build() {
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }

      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
	// 默认使用OkHttpClient
        callFactory = new OkHttpClient();
      }

      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        // 获取回调方法的任务调度,该Executor持有主线程的Handler,应该是用于向主线程发送网络响应结果的
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      // Make a defensive copy of the adapters and add the default Call adapter.
      List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
      // 默认添加ExecutorCallAdapterFactory类
      callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // Make a defensive copy of the converters.
      List<Converter.Factory> converterFactories =
          new ArrayList<>(1 + this.converterFactories.size());

      // Add the built-in converter factory first. This prevents overriding its behavior but also
      // ensures correct behavior when using converters that consume all types.
      // 默认添加BuiltInConverters
      converterFactories.add(new BuiltInConverters());
      converterFactories.addAll(this.converterFactories);

      return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
          unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
    }

创建代理类

Retrofit的create方法创建Proxy类

  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();

          @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.
            // 如果执行的是Object的方法,则直接运行method的invoke
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            // 默认为false
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            // 创建并获取ServiceMethod
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            // 创建OkHttpCall
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            // 返回Call请求
            return serviceMethod.adapt(okHttpCall);
          }
        });
  }

当调用代理类的方法时,会执行InvocationHandler的invoke方法。

创建ServiceMethod

在调用网络请求方法时,ServiceMethod是将参数与对应的方法注解进行合成,构成符合用户要求的网络请求。

Retrofit的loadServiceMethod方法从缓存中获取一个方法对应的ServiceMethod,存在就返回,不存在就创建并保存到缓存中再返回。

  private final Map<Method, ServiceMethod<?, ?>> serviceMethodCache = new ConcurrentHashMap<>();

  ServiceMethod<?, ?> loadServiceMethod(Method method) {
    // 从缓存中获取method对应的ServiceMethod,ServiceMethod可以认为是method的解析
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值