Retrofit2 源码分析

Retrofit介绍

Retrofit是Square公司的一个开源网络访问框架。主要是把网络请求的数据,通过接口来封装。内部通过OKHttpClient来请求。

Retrofit的简单配置,使用

 Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl("https://api.xxx.com/")
                .build();
        APIService service = retrofit.create(APIService.class);
        Call call = service.getList("PRODUCT");
        try {
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {}
                @Override
                public void onFailure(Call call, Throwable t) {}
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    ....

    @GET("product/list")
    Call getList(@Query String type);

下面,我们就从上面的调用,开始分析下Retrofit的大致流程。

Retrofit 分析

主要属性:
- Platform
- callFactory
- baseUrl
- converterFactories
- adapterFactories
- callbackExecutor

1.首先,从它的配置开始分析。new Retrofit.Builder()

看下源代码


    public Builder() {
      this(Platform.get());
    }

    Builder(Platform platform) {
      this.platform = platform;

      converterFactories.add(new BuiltInConverters());
    }

这里主要做了两件事。

  • 1,获取了一个Platform.
  • 2,给converterFactories集合添加了一个BuiltInConverters(转换器).

我们分别看下Platfor跟BuiltInConverters的内容。

1.1 ,先看下Platform的生成

private static final Platform PLATFORM = findPlatform();

  static Platform get() {
    return PLATFORM;
  }
    //这里我们只看Android平台
  private static Platform findPlatform() {
    try {
      Class.forName("android.os.Build");
      if (Build.VERSION.SDK_INT != 0) {
        return new Android();
      }
    } catch (ClassNotFoundException ignored) {
    }
    try {
      Class.forName("java.util.Optional");
      return new Java8();
    } catch (ClassNotFoundException ignored) {
    }
    return new Platform();
  }
=========================
Android类型的Platform
static class Android extends Platform {
    @Override public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }

    @Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
      if (callbackExecutor == null) throw new AssertionError();
        //Platform返回的CallAdapter.Factory
      return new ExecutorCallAdapterFactory(callbackExecutor);
    }

    static class MainThreadExecutor implements Executor {
        //主线程Handler.
      private final Handler handler = new Handler(Looper.getMainLooper());

      @Override public void execute(Runnable r) {
        handler.post(r);
      }
    }
  }


这里我们可以看到
- Platform使用的是 Android 的平台。
- MainThreadExecutor就是把执行的内容放到了主线程。
- platform返回的CallAdapter.Factory是ExecutorCallAdapterFactory

1.2,看下BuiltInConverters

final class BuiltInConverters extends Converter.Factory {
  @Override
  public Converter responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    if (type == ResponseBody.class) {
      return Utils.isAnnotationPresent(annotations, Streaming.class)
          ? StreamingResponseBodyConverter.INSTANCE
          : BufferingResponseBodyConverter.INSTANCE;
    }
    if (type == Void.class) {
      return VoidResponseBodyConverter.INSTANCE;
    }
    return null;
  }

如果type是ResponseBody的话
如果是流,就返回StreamingResponseBodyConverter
否则,就返回BufferingResponseBodyConverter
否则,返回null

2,Retrofit的build()方法

 public Retrofit build() {
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }
        //这里默认使用的是OkHttpClient
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
        //这里没有设置的话,用的就是上面分析的Android里面获取的MainThreadExecutor
      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      List adapterFactories = new ArrayList<>(this.adapterFactories);
        //添加ExecutorCallAdapterFactory
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // converterFactories里面有个默认的BuiltInConverters。
      List converterFactories = new ArrayList<>(this.converterFactories);
        //生成Retrofit
      return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
          callbackExecutor, validateEagerly);
    }
==========================
//Retrofit里面的属性都是不可变的
final okhttp3.Call.Factory callFactory;
  final HttpUrl baseUrl;
  final List converterFactories;
  final List adapterFactories;
  final @Nullable Executor callbackExecutor;
  final boolean validateEagerly;

  Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
      List converterFactories, List adapterFactories,
      @Nullable Executor callbackExecutor, boolean validateEagerly) {
    this.callFactory = callFactory;
    this.baseUrl = baseUrl;
    this.converterFactories = unmodifiableList(converterFactories); // Defensive copy at call site.
    this.adapterFactories = unmodifiableList(adapterFactories); // Defensive copy at call site.
    this.callbackExecutor = callbackExecutor;
    this.validateEagerly = validateEagerly;
  }


到这里,配置就看完了。
Retrofit里面的属性:
- callFactory 是OKHttpClient
- baseUrl就是传入的url
- converterFactories 里面有个默认的BuiltInConverters
- adapterFactories 里面有个ExecutorCallAdapterFactory
- callbackExecutor 就是Android里面的MainThreadExecutor

3,看下他的调用,生成call

//调用方法
ApiService service = retrofit.create(ApiService.class);
Call call = service.getList("product");

源码,看下create()方法

public  T create(final Class 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 {
            // 如果是Object的方法,直接过滤
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            //默认是false
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            //注释1。获取ServiceMethod对象
            ServiceMethod serviceMethod =
                (ServiceMethod) loadServiceMethod(method);
            //注释2。通过serviceMethod和参数,构建OKHttpCall
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            //注释3,调用adapt方法
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }
 
  

这里面有三个注释,我们需要看

3.1,注释1 ,获取ServiceMethod对象

 ServiceMethod, ?> loadServiceMethod(Method method) {
    //如果缓存有,直接返回
    ServiceMethod, ?> result = serviceMethodCache.get(method);
    if (result != null) return result;
    //同步
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        //注释3.1.1。如果缓存没有,初始化(持有retrofit,method),并放入缓存
        result = new ServiceMethod.Builder<>(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }
注释3.1.1。
Builder(Retrofit retrofit, Method method) {
      this.retrofit = retrofit;
      this.method = method;
        //方法上面的注解(@GET("xxxx"),@POST等等)
      this.methodAnnotations = method.getAnnotations();
        //方法的形参类型
      this.parameterTypes = method.getGenericParameterTypes();
        //获取形参注解getList(@Part这些)
      this.parameterAnnotationsArray = method.getParameterAnnotations();
    }

    public ServiceMethod build() {
        //3.1.1.1 生成CallAdapter
      callAdapter = createCallAdapter();
        //3.1.1.2 拿到CallAdapter返回值类型
      responseType = callAdapter.responseType();
      if (responseType == Response.class || responseType == okhttp3.Response.class) {
        throw methodError("'"
            + Utils.getRawType(responseType).getName()
            + "' is not a valid response body type. Did you mean ResponseBody?");
      }
        //3.1.1.3获取conveter
      responseConverter = createResponseConverter();
        //处理方法上的注解
      for (Annotation annotation : methodAnnotations) {
        parseMethodAnnotation(annotation);
      }
        ...
        //处理形参的注解
      int parameterCount = parameterAnnotationsArray.length;
      parameterHandlers = new ParameterHandler[parameterCount];
      for (int p = 0; p < parameterCount; p++) {
        Type parameterType = parameterTypes[p];

        Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
        if (parameterAnnotations == null) {
          throw parameterError(p, "No Retrofit annotation found.");
        }

        parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
      }

     ...
      return new ServiceMethod<>(this);
    }

里面的操作非常多。几个注释的地方,一个个来看

3.1.1.1 首先看下生成CallAdapter
private CallAdapter createCallAdapter() {
        //获取方法返回类型Call
      Type returnType = method.getGenericReturnType();
        //获取方法的注解 (@GET,@POST等)
      Annotation[] annotations = method.getAnnotations();
      try {
        //调用retrofit的callAdapter来生成CallAdapter
        return (CallAdapter) retrofit.callAdapter(returnType, annotations);
      } catch (RuntimeException e) { // Wide exception range because factories are user code.
        throw methodError(e, "Unable to create call adapter for %s", returnType);
      }
    }

    ...
    //retrofit的callAdapter方法
    public CallAdapter callAdapter(Type returnType, Annotation[] annotations) {
    return nextCallAdapter(null, returnType, annotations);
  }
    ...
    //nextCallAdapter方法

    public CallAdapter nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
      Annotation[] annotations) {
    //第一个参数为null。所以这里start是从0开始的
    int start = adapterFactories.indexOf(skipPast) + 1;
    //遍历adapterFactories(初始化会有一个ExecutorCallAdapterFactory,上面说过),找到符合类型跟注解的CallAdapter
    for (int i = start, count = adapterFactories.size(); i < count; i++) {
      CallAdapter adapter = adapterFactories.get(i).get(returnType, annotations, this);
      if (adapter != null) {
        return adapter;
      }
    }
==============
    ExecutorCallAdapterFactory.java
    @Override
  public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
    //不是Call类型的,直接返回Null
    if (getRawType(returnType) != Call.class) {
      return null;
    }
    //获取Call里面的T类型
    final Type responseType = Utils.getCallResponseType(returnType);
    return new CallAdapter>() {
      @Override public Type responseType() {
        return responseType;
      }

      @Override public Call adapt(Call call) {
        return new ExecutorCallbackCall<>(callbackExecutor, call);
      }
    };
  }
 
  

到这里,我们就看到了CallAdapter的创建过程,它是利用接口的返回类型跟注解来生成的。

3.1.1.2 callAdapter.responseType()

下面,来看下callAdapter.responseType()

      @Override public Type responseType() {
        //直接返回T的类型
        return responseType;
      }

下面,我们来看看,创建Conveter

3.1.1.3 createResponseConverter()
ServiceMethod.java

  private Converter createResponseConverter() {
        //获取注解
      Annotation[] annotations = method.getAnnotations();
      try {
        //把响应类型跟注解,传过去
        return retrofit.responseBodyConverter(responseType, annotations);
      } catch (RuntimeException e) { // Wide exception range because factories are user code.
        throw methodError(e, "Unable to create converter for %s", responseType);
      }
    }

    ...

Retrofit.java

  public  Converter responseBodyConverter(Type type, Annotation[] annotations) {
    return nextResponseBodyConverter(null, type, annotations);
  }
    ---
 public  Converter nextResponseBodyConverter(
      @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
    checkNotNull(type, "type == null");
    checkNotNull(annotations, "annotations == null");
    //也是从0开始
    //找到合适的转换器转换类型
    int start = converterFactories.indexOf(skipPast) + 1;
    for (int i = start, count = converterFactories.size(); i < count; i++) {
      Converter converter =
          converterFactories.get(i).responseBodyConverter(type, annotations, this);
      if (converter != null) {
        //noinspection unchecked
        return (Converter) converter;
      }
    }


上面分析了这里的converterFactories里面 会有一个默认的BuiltInConverters转换器
我们一般也会加上一个Gson的转换器。
这里就是把ResponseBody转换成我们想要的T类型。

BuiltInConverters.java

@Override
  public Converter responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    if (type == ResponseBody.class) {
      return Utils.isAnnotationPresent(annotations, Streaming.class)
          ? StreamingResponseBodyConverter.INSTANCE
          : BufferingResponseBodyConverter.INSTANCE;
    }
    if (type == Void.class) {
      return VoidResponseBodyConverter.INSTANCE;
    }
    return null;
  }

GsonConverterFactory.java
  @Override
  public Converter responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    TypeAdapter adapter = gson.getAdapter(TypeToken.get(type));
    return new GsonResponseBodyConverter<>(gson, adapter);
  }


到这里,我们知道Converter其实就是BuiltInConverters或者GsonResponseBodyConverter等我们自己添加的转换器。

处理注解这块,暂时不看。

确定查看ServiceMethod里面的属性值

  • callFactory OKHttpClient
  • callAdapter ExecutorCallAdapter

4,构建OkHttpCall


  OkHttpCall(ServiceMethod serviceMethod, @Nullable Object[] args) {
    this.serviceMethod = serviceMethod;
    this.args = args;
  }

OKHttpCall持有ServcieMethod跟参数

5,调用adapt方法,生成接口实例APIService

这里其实就是调用ExecutorCallAdapterFactory的adapt方法

ExecutorCallAdapterFactory.java
//调用的就是它的get方法,生成的CallAdapter
 public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        if (getRawType(returnType) != Call.class) {
            return null;
        } else {
            final Type responseType = Utils.getCallResponseType(returnType);
            return new CallAdapter>() {
                public Type responseType() {
                    return responseType;
                }

                public Call adapt(Call call) {
                    return new ExecutorCallAdapterFactory.ExecutorCallbackCall(ExecutorCallAdapterFactory.this.callbackExecutor, call);
                }
            };
        }
    }

   ExecutorCallbackCall(Executor callbackExecutor, Call delegate) {
            this.callbackExecutor = callbackExecutor;
            this.delegate = delegate;
        }

 
  

最终就是生成ExecutorCallbackCall。

调用enqueue获取结果

public void enqueue(final Callback callback) {
            Utils.checkNotNull(callback, "callback == null");
            //这里delegate就是OKHttpCall
            this.delegate.enqueue(new Callback() {
                public void onResponse(Call call, final Response response) {
                    //这里的callbackExecutor其实就是MainThreadExecutor
                    ExecutorCallbackCall.this.callbackExecutor.execute(new Runnable() {
                        public void run() {
                            if (ExecutorCallbackCall.this.delegate.isCanceled()) {
                                callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
                            } else {
                                callback.onResponse(ExecutorCallbackCall.this, response);
                            }

                        }
                    });
                }

                public void onFailure(Call call, final Throwable t) {
                    ExecutorCallbackCall.this.callbackExecutor.execute(new Runnable() {
                        public void run() {
                            callback.onFailure(ExecutorCallbackCall.this, t);
                        }
                    });
                }
            });
        }
================
OKHttpCall.java
 @Override public void enqueue(final Callback callback) {
    checkNotNull(callback, "callback == null");

    okhttp3.Call call;
      call = rawCall;
      if (call == null && failure == null) {
        try {
          call = rawCall = createRawCall();
        } catch (Throwable t) {
          failure = creationFailure = t;
        }
      }
    }

    if (failure != null) {
      callback.onFailure(this, failure);
      return;
    }

    if (canceled) {
      call.cancel();
    }

    call.enqueue(new okhttp3.Callback() {
      @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
          throws IOException {
        Response response;
        try {
          response = parseResponse(rawResponse);
        } catch (Throwable e) {
          callFailure(e);
          return;
        }
        callSuccess(response);
      }

      @Override public void onFailure(okhttp3.Call call, IOException e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callFailure(Throwable e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callSuccess(Response response) {
        try {
          callback.onResponse(OkHttpCall.this, response);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    });
  }

createRawCall()方法

  private okhttp3.Call createRawCall() throws IOException {
    //调用serviceMethod的请求来,构建OKHttp的Request对象
    Request request = serviceMethod.toRequest(args);
    //通过callFactory来生成okhttp3的call
    okhttp3.Call call = serviceMethod.callFactory.newCall(request);
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
  }

整体的调用过程:

一、先初始化生成Retrofit:

二、Call call = retrofit.create();

1,生成ServiceMethod

2,生成OKHttpCall

  OkHttpCall(ServiceMethod serviceMethod, @Nullable Object[] args) {
    this.serviceMethod = serviceMethod;
    this.args = args;
  }

3,生成返回对象Call

三、Call.enqueue()方法调用


Retrofit—>ServiceMethod(解析注解,构造okhttp3需要的request,response等)—>OKHttpCall(内部调用serviceMethod的方法构建okhttp3.call来完成联网请求)

参考:https://juejin.im/post/5a30fa41f265da43085e0650

你可能感兴趣的:(Android-源码分析)