retrofit解析

retrofit解析

1.retrofit build

 /**
     * Set the API base URL.
     *
     * @see #baseUrl(HttpUrl)
     */
    public Builder baseUrl(String baseUrl) {
      checkNotNull(baseUrl, "baseUrl == null");
      HttpUrl httpUrl = HttpUrl.parse(baseUrl);
      if (httpUrl == null) {
        throw new IllegalArgumentException("Illegal URL: " + baseUrl);
      }
      return baseUrl(httpUrl);
    }


    public Builder baseUrl(HttpUrl baseUrl) {
      checkNotNull(baseUrl, "baseUrl == null");
      List<String> pathSegments = baseUrl.pathSegments();
      if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
        throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
      }
      this.baseUrl = baseUrl;
      return this;
    }

    public Retrofit build() {
      if (baseUrl == null) {// 必须设置baseUrl, 从上面设置baseUrl可以看出baseUrl不能为null及不包含"/"的url,若不用baseUrl可以设置为"/"
        throw new IllegalStateException("Base URL required.");
      }

      okhttp3.Call.Factory callFactory = this.callFactory;// 执行请求的工厂类,默认为okhttp
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }

      Executor callbackExecutor = this.callbackExecutor;// 请求执行完后, 回调执行器, android默认把请求结果发送到ui线程
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      // Make a defensive copy of the adapters and add the default Call adapter.
      List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);// 转变请求的适配器工厂
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // Make a defensive copy of the converters.
      List<Converter.Factory> converterFactories =
          new ArrayList<>(1 + this.converterFactories.size());// 对请求结果及请求参数的转变工厂, 当service方法中参数注解为(@Part, @PartMap, @Body)时要提供转换工厂重写请求转换

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

    // validateEagerly 提前缓存service方法, 不用到请求时再去解析service方法
      return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
          callbackExecutor, validateEagerly);
    }

2.创建service代理

    public <T> T create(final Class<T> service) {
        Utils.validateServiceInterface(service);
        if (validateEagerly) {//提前缓存service方法
          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.
                if (method.getDeclaringClass() == Object.class) {// 这个没看懂有什么用
                  return method.invoke(this, args);
                }
                if (platform.isDefaultMethod(method)) {// java8 接口默认方法,直接执行
                  return platform.invokeDefaultMethod(method, service, proxy, args);
                }
                ServiceMethod<Object, Object> serviceMethod =
                    (ServiceMethod<Object, Object>) loadServiceMethod(method);// 解析缓存service方法
                OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
                return serviceMethod.callAdapter.adapt(okHttpCall);// call适配器开始转变call, 若没有提供converterFactories, service方法只能返回Call<ResponseBody> Call<Void>类型
              }
            });
    }

    final class BuiltInConverters extends Converter.Factory {// 默认数据转换器
      @Override
      public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
          Retrofit retrofit) {
        if (type == ResponseBody.class) {// service方法只能返回Call<ResponseBody> Call<Void>类型
          return Utils.isAnnotationPresent(annotations, Streaming.class)
              ? StreamingResponseBodyConverter.INSTANCE
              : BufferingResponseBodyConverter.INSTANCE;
        }
        if (type == Void.class) {
          return VoidResponseBodyConverter.INSTANCE;
        }
        return null;
        }
        ...
    }
    final class DefaultCallAdapterFactory extends CallAdapter.Factory {// 默认call适配器 android平台默认为ExecutorCallAdapterFactory
      static final CallAdapter.Factory INSTANCE = new DefaultCallAdapterFactory();

      @Override
      public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        if (getRawType(returnType) != Call.class) {// service方法只能返回Call类型
          return null;
        }
        ...
    }
OkHttpCall:
    // 调用Retrofit的Call的execute()执行下面方法, 
    private okhttp3.Call createRawCall() throws IOException {
        Request request = serviceMethod.toRequest(args);// 把service方法转成okhttp请求参数
        okhttp3.Call call = serviceMethod.callFactory.newCall(request);// 通过设置的okhttpclient创建一个okhttp call, 前面所说的Call都为Retrofit的Call类
        if (call == null) {
          throw new NullPointerException("Call.Factory returned null.");
        }
        return call;
  }

3.loadServiceMethod原理探究

    // 方法注解
    Annotation[] methodAnnotations = mMethod.getAnnotations();

    // 方法参数类型
    Type[] types = mMethod.getGenericParameterTypes();
    // 方法参数注解
    Annotation[][] parameterAnnotationsArray = mMethod.getParameterAnnotations();

   for(int i = 0; i < types.length; i++)
    {
        Annotation[] parameterAnnotations = parameterAnnotationsArray[i];
        for(Annotation annotation : parameterAnnotations)
        {
           annotation.value();// 注解值
        }

    }
    原理就如上面代码所示, retrofit对获取到注解信息做了很多处理ParameterHandler类

猜你喜欢

转载自blog.csdn.net/a90123/article/details/78135412