Retrofit源码解析

Retrofit 使用
  • 1.定义请求接口
public interface GitHubService {

    @GET("users")
    Call<User> getUser(@Query("id") int userId);

}
  • 2.构建Retrofit 实例
   Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
  • 3.创建接口的动态代理类,调用接口里的方法
        GitHubService service = retrofit.create(GitHubService.class);
  • 4.发起网络请求,处理回调接口
 service.getUser(1).enqueue(new retrofit2.Callback<User>() {
            @Override
            public void onResponse(retrofit2.Call<User> call, retrofit2.Response<User> response) {

            }

            @Override
            public void onFailure(retrofit2.Call<User> call, Throwable t) {

            }
        });
Retrofit 源码分析

在这里插入图片描述

关键接口

Call:可以理解为一个完整的 http 请求活动,向服务器发起请求(Request)和得到返回结果(Response)。
CallAdapter:可以把 Call 对象转化成另一个对象,如 Observable
Converter:把数据进行转化,这个接口里面有三个转换器responseBodyConverterrequestBodyConverterstringConverter
Callbackhttp请求回调

第一步:Retrofit 构建
public Retrofit build() {
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }
//设置okhttp callFactory
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
//设置executer,一般不设置使用默认的,对于Android来说就是一个使用Handler切换到主线程的executer
      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      // 设置CallAdapter.factory 列表
      List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // 设置 Converter.factory 列表
      List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);

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

可以看到,除了baseUrl 必须要添加,还有2个可选的参数。

  1. Converter 的实现对象的工厂类
  2. CallAdapter 的实现对象的工厂类
    创建了List<CallAdapter.Factory>List<Converter.Factory> 用来存放传进来的参数。
    第一步先到这里,先王下走。
第二步: create()创建方法的接口
public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service); //1
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
        //获取当前平台  这里为Android
          private final Platform platform = Platform.get();

          @Override public Object invoke(Object proxy, Method method, 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);
            }
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
			//获取一个ServiceMethod对象构建一个Call对象
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

使用Proxy.newProxyInstance创建了方法接口的一个动态代理对象,调用方法的时候进入invoke回调。

我们简单看下create里面都做了什么

  1. 判断接口是否合法,方法数是否大于0
    Utils.validateServiceInterface(service)
static <T> void validateServiceInterface(Class<T> service) {
    if (!service.isInterface()) {
      throw new IllegalArgumentException("API declarations must be interfaces.");
    }
    // Prevent API interfaces from extending other interfaces. This not only avoids a bug in
    // Android (http://b.android.com/58753) but it forces composition of API declarations which is
    // the recommended pattern.
    if (service.getInterfaces().length > 0) {
      throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
    }
  }
  1. 预先加载接口中的所有方法
    eagerlyValidateMethods(service)
  private void eagerlyValidateMethods(Class<?> service) {
    Platform platform = Platform.get();
    for (Method method : service.getDeclaredMethods()) {
      if (!platform.isDefaultMethod(method)) {
        loadServiceMethod(method);
      }
    }
  }
第三步:调用接口中的方法

由第二步可以知道,调用接口的方法,其实是调用了刚才创建的代理对象中的方法,然后进入invoke方法。所以调用的是下面这段代码。(一般情况下是这样调用的,这里先不考虑其它情况)

ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);

我们分析下这段代码

1. 加载接口方法

ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);

 ServiceMethod<?, ?> loadServiceMethod(Method method) {
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
    if (result != null) return result;

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = new ServiceMethod.Builder<>(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

主要作用是通过反射的Method对象获取一个ServiceMethod对象。

首先从cache 中获取一个 ServiceMethod,如果没有,就创建一个新的ServiceMethod,在存入cache。

前面我们已经知道,ServiceMethod可以进行预加载,默认使用懒加载(调用的时候加载),如果对方调用有时间要求,可以使用预先加载,减少一些时间。

下面来看ServiceMethod 的创建

    public ServiceMethod build() {
      callAdapter = createCallAdapter();
      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?");
      }
      responseConverter = createResponseConverter();

      for (Annotation annotation : methodAnnotations) {
        parseMethodAnnotation(annotation);
      }

      if (httpMethod == null) {
        throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
      }

      if (!hasBody) {
        if (isMultipart) {
          throw methodError(
              "Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
        }
        if (isFormEncoded) {
          throw methodError("FormUrlEncoded can only be specified on HTTP methods with "
              + "request body (e.g., @POST).");
        }
      }

      int parameterCount = parameterAnnotationsArray.length;
      parameterHandlers = new ParameterHandler<?>[parameterCount];
      for (int p = 0; p < parameterCount; p++) {
        Type parameterType = parameterTypes[p];
        if (Utils.hasUnresolvableType(parameterType)) {
          throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
              parameterType);
        }

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

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

      if (relativeUrl == null && !gotUrl) {
        throw methodError("Missing either @%s URL or @Url parameter.", httpMethod);
      }
      if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
        throw methodError("Non-body HTTP method cannot contain @Body.");
      }
      if (isFormEncoded && !gotField) {
        throw methodError("Form-encoded method must contain at least one @Field.");
      }
      if (isMultipart && !gotPart) {
        throw methodError("Multipart method must contain at least one @Part.");
      }

      return new ServiceMethod<>(this);
    }

创建ServiceMethod有2个参数,一个是Retrofit对象,一个是Method对象。

可以看到,这个方法中抛出很多异常,大部分是注解用错了。

这里主要内容有3点

  • 1.创建CallAdapter 对象
  • 2.创建Converter 对象
  • 3.对接口方法的注解进行解析

我们一个个来看下:


callAdapter = createCallAdapter()

 private CallAdapter<T, R> createCallAdapter() {
      Type returnType = method.getGenericReturnType();
      if (Utils.hasUnresolvableType(returnType)) {
        throw methodError(
            "Method return type must not include a type variable or wildcard: %s", returnType);
      }
      if (returnType == void.class) {
        throw methodError("Service methods cannot return void.");
      }
      Annotation[] annotations = method.getAnnotations();
      try {
        //noinspection unchecked
        return (CallAdapter<T, R>) 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);
      }
    }

(CallAdapter<T, R>) retrofit.callAdapter(returnType, annotations)

 public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
    return nextCallAdapter(null, returnType, annotations);
  }

  /**
   * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
   * #callAdapterFactories() factories} except {@code skipPast}.
   *
   * @throws IllegalArgumentException if no call adapter available for {@code type}.
   */
  public CallAdapter<?, ?> nextCallAdapter(CallAdapter.Factory skipPast, Type returnType,
      Annotation[] annotations) {
    checkNotNull(returnType, "returnType == null");
    checkNotNull(annotations, "annotations == null");

    int start = adapterFactories.indexOf(skipPast) + 1;
    for (int i = start, count = adapterFactories.size(); i < count; i++) {
      CallAdapter<?, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);
      if (adapter != null) {
        return adapter;
      }
    }

    StringBuilder builder = new StringBuilder("Could not locate call adapter for ")
        .append(returnType)
        .append(".\n");
    if (skipPast != null) {
      builder.append("  Skipped:");
      for (int i = 0; i < start; i++) {
        builder.append("\n   * ").append(adapterFactories.get(i).getClass().getName());
      }
      builder.append('\n');
    }
    builder.append("  Tried:");
    for (int i = start, count = adapterFactories.size(); i < count; i++) {
      builder.append("\n   * ").append(adapterFactories.get(i).getClass().getName());
    }
    throw new IllegalArgumentException(builder.toString());
  }

创建CallAdapter 主要调用 Retrofit中的nextCallAdapter,从adapterFactories中获取一个Factory 去创建对应的 CallAdapter。如果 adapterFactories 中所有的 Factory都无法创建对应的 CallAdapter 则会报错。

 public Retrofit build() {
     ...
      List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
      ...
    }
  }

前面在创建adapterFactories对象时,会预先在里面添加一个默认的CallAdapter.Factory


创建Converter 的过程和 CallAdapter 是一致的

Builder(Platform platform) {
      this.platform = platform;
      // 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());
    }
...
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
...

有点不太一样的地方是在创建Retrofit.Build对象的时候,就先把默认的Converter也就是BuiltInConverters添加到了converterFactories中。


由于Retrofit的注解比较多,所以对接口方法进行注解解析的过程比较复杂。这里简单看下:
解析注释,分两部分,一部分是解析方法上的注释,一部分是解析参数上的注释。

 public ServiceMethod build() {
      ...
      for (Annotation annotation : methodAnnotations) {
        parseMethodAnnotation(annotation);
      }

      ...
      for (int p = 0; p < parameterCount; p++) {
        ...
        parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
      }
      ...
      return new ServiceMethod<>(this);
    }
  1. 方法上的注释:
    parseMethodAnnotation
 private void parseMethodAnnotation(Annotation annotation) {
      if (annotation instanceof DELETE) {
        parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
      } else if (annotation instanceof GET) {
        parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
      } else if (annotation instanceof HEAD) {
        parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
        if (!Void.class.equals(responseType)) {
          throw methodError("HEAD method must use Void as response type.");
        }
      } else if (annotation instanceof PATCH) {
        parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
      } else if (annotation instanceof POST) {
        parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
      } else if (annotation instanceof PUT) {
        parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
      } else if (annotation instanceof OPTIONS) {
        parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
      } else if (annotation instanceof HTTP) {
        HTTP http = (HTTP) annotation;
        parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
      } else if (annotation instanceof retrofit2.http.Headers) {
        String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
        if (headersToParse.length == 0) {
          throw methodError("@Headers annotation is empty.");
        }
        headers = parseHeaders(headersToParse);
      } else if (annotation instanceof Multipart) {
        if (isFormEncoded) {
          throw methodError("Only one encoding annotation is allowed.");
        }
        isMultipart = true;
      } else if (annotation instanceof FormUrlEncoded) {
        if (isMultipart) {
          throw methodError("Only one encoding annotation is allowed.");
        }
        isFormEncoded = true;
      }
    }

方法上的注解,就是判断不同注解进行不同的解析,然后给一些变量赋值。

  1. 方法上的注解
    parseParameter
  private ParameterHandler<?> parseParameter(
        int p, Type parameterType, Annotation[] annotations) {
      ParameterHandler<?> result = null;
      for (Annotation annotation : annotations) {
        ParameterHandler<?> annotationAction = parseParameterAnnotation(
            p, parameterType, annotations, annotation);

        if (annotationAction == null) {
          continue;
        }

        if (result != null) {
          throw parameterError(p, "Multiple Retrofit annotations found, only one allowed.");
        }

        result = annotationAction;
      }

      if (result == null) {
        throw parameterError(p, "No Retrofit annotation found.");
      }

      return result;
    }

就是把参数上的注解转化为ParameterHandler对象,接下来看ParameterHandler对象:

abstract class ParameterHandler<T> {
  abstract void apply(RequestBuilder builder, T value) throws IOException;
  final ParameterHandler<Iterable<T>> iterable() {
    return new ParameterHandler<Iterable<T>>() {
      @Override void apply(RequestBuilder builder, Iterable<T> values) throws IOException {
     ...
    };
  }

  final ParameterHandler<Object> array() {
    return new ParameterHandler<Object>() {
      @Override void apply(RequestBuilder builder, Object values) throws IOException {
       ...
      }
    };
  }

  static final class RelativeUrl extends ParameterHandler<Object> {
    @Override void apply(RequestBuilder builder, Object value) {
      builder.setRelativeUrl(value);
    }
  }

  static final class Header<T> extends ParameterHandler<T> {
    ...
  }

  static final class Path<T> extends ParameterHandler<T> {
    ...
  }

  static final class Query<T> extends ParameterHandler<T> {
   ...
  }

  static final class QueryMap<T> extends ParameterHandler<Map<String, T>> {
    ...
  }

  static final class Field<T> extends ParameterHandler<T> {
  ...
  }

  static final class FieldMap<T> extends ParameterHandler<Map<String, T>> {
    ...
  }

  static final class Part<T> extends ParameterHandler<T> {
    ...
  }

  static final class RawPart extends ParameterHandler<MultipartBody.Part> {
   ...
  }

  static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
   ...
  }

  static final class Body<T> extends ParameterHandler<T> {
    ...
}

所有的注解对应的都有自己的一个ParameterHandler实现。然后进行里面的解析。


解析方法注释得到的参数,以及解析方法参数的注释得到的 ParameterHandler都是为了构建Request对象,代码如下:

//ServiceMethod.java
  Request toRequest(Object... args) throws IOException {
    RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
        contentType, hasBody, isFormEncoded, isMultipart);

    @SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
    ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;

    int argumentCount = args != null ? args.length : 0;
    if (argumentCount != handlers.length) {
      throw new IllegalArgumentException("Argument count (" + argumentCount
          + ") doesn't match expected count (" + handlers.length + ")");
    }

    for (int p = 0; p < argumentCount; p++) {
      handlers[p].apply(requestBuilder, args[p]);
    }

    return requestBuilder.build();
  }

其中handlers[p].apply(requestBuilder, args[p])循环调用ParameterHandler这个抽象类的抽象方法。


2. 创建OkHttpCall对象

OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);

  @Override public OkHttpCall<T> clone() {
    return new OkHttpCall<>(serviceMethod, args);
  }

OkHttpCall的构造方法很简单,OkHttpCall实现了Call接口。

3.CallAdapter 对Call 对象进行转换

先来看下前面默认的CallAdapter;
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
这里需要知道Platform

class Platform {
 ..
  }
  static class Android extends Platform {
    @Override public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }

    @Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
      return new ExecutorCallAdapterFactory(callbackExecutor);
    }

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

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

}

对不同的平台进行了不同的处理,这里是Android平台,所以调用Android中的方法。

所以默认的CallAdapter.FactoryExecutorCallAdapterFactory,下面我们继续刚才重要的第3句代码
return serviceMethod.callAdapter.adapt(okHttpCall)

final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
 ...
  @Override
  public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
    if (getRawType(returnType) != Call.class) {
      return null;
    }
    final Type responseType = Utils.getCallResponseType(returnType);
    return new CallAdapter<Call<?>>() {
      @Override public Type responseType() {
        return responseType;
      }

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

  static final class ExecutorCallbackCall<T> implements Call<T> {
    final Executor callbackExecutor;
    final Call<T> delegate;

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

    @Override public void enqueue(final Callback<T> callback) {
      if (callback == null) throw new NullPointerException("callback == null");

      delegate.enqueue(new Callback<T>() {
        @Override public void onResponse(Call<T> call, final Response<T> response) {
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              if (delegate.isCanceled()) {
                // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
                callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
              } else {
                callback.onResponse(ExecutorCallbackCall.this, response);
              }
            }
          });
        }

        @Override public void onFailure(Call<T> call, final Throwable t) {
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              callback.onFailure(ExecutorCallbackCall.this, t);
            }
          });
        }
      });
    }
...

使用adapter方法后返回ExecutorCallbackCall这个对象

第四步:enqueue发送请求(execute 差不多)

由上面可知,调用接口方法后,真正返回的是ExecutorCallbackCall对象。

调用enqueue方法,其实是调用创建ExecutorCallbackCall对象传入的Call 对象。(其实是OkhttpCall对象)

//OkhttpCall.java
@Override public void enqueue(final Callback<T> callback) {
    ...
    call = rawCall = createRawCall();
    ...
    call.enqueue(new okhttp3.Callback() {
      @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
          throws IOException {
          ...
          response = parseResponse(rawResponse);
         ...
    });
  }
...
private okhttp3.Call createRawCall() throws IOException {
    Request request = serviceMethod.toRequest(args);
    okhttp3.Call call = serviceMethod.callFactory.newCall(request);
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
  }
...
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
     ...
      T body = serviceMethod.toResponse(catchingBody);
      return Response.success(body, rawResponse);
     ...
  }

其中有两个重要的方法 createRawCallparseResponse


createRawCall
这里主要调用了serviceMethod.toRequest(args)其实在前面我们知道,ServiceMethod中的toRequest就是把前面解析完成的参数转化为对应的Request

这里我们还要了解serviceMethod.callFactory

//ServiceMethod.java
ServiceMethod(Builder<R, T> builder) {
    this.callFactory = builder.retrofit.callFactory();
    ...
   }
//Retrofit.java
...
 public Builder client(OkHttpClient client) {
      return callFactory(checkNotNull(client, "client == null"));
    }

    /**
     * Specify a custom call factory for creating {@link Call} instances.
     * <p>
     * Note: Calling {@link #client} automatically sets this value.
     */
    public Builder callFactory(okhttp3.Call.Factory factory) {
      this.callFactory = checkNotNull(factory, "factory == null");
      return this;
    }
...
 public Retrofit build() {
      ...
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
      ...
...

由上可看出,ServiceMethod中的callFactory就是Retrofit中的callFactory,可以在构造Retrofit对象的时候传入,不传入默认为OkHttpClient

所以okhttp3.Call call = serviceMethod.callFactory.newCall(request);
这里的serviceMethod.callFactory其实就是OkHttpClient,然后创建了一个Call对象。真正发起请求的也是这个Call对象。
这里的Callokhttp3.call,前面说的Callretrofit2.Call,不要搞混。

其实Retrofit可以理解为在OkHttp外面的一层封装,真正去发生http请求的还是在okhttp里。


parseResponse
来看它里面重要的一句:
T body = serviceMethod.toResponse(catchingBody);

//ServiceMethod.java
...
this.responseConverter = builder.responseConverter;
...
T toResponse(ResponseBody body) throws IOException {
    return responseConverter.convert(body);
  }
...

使用Convert对象把ResponseBody转化为另一个对象。由代码可看出,ServiceMethod中的responseConverter也是来自Retrofit对象。就是前面说的默认的converter.Factory对象,也就是BuiltInConverters,产生的Convert对象。

final class BuiltInConverters extends Converter.Factory {
  @Override
  public Converter<ResponseBody, ?> 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;
  }

ServiceMethod中会根据方法的返回类型,在里面获得到对应的Converter对象。如果返回的类型没有相应的Converter则返回null。

//Retrofit.java
  public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
      Type type, Annotation[] annotations) {
    checkNotNull(type, "type == null");
    checkNotNull(annotations, "annotations == null");

    int start = converterFactories.indexOf(skipPast) + 1;
    for (int i = start, count = converterFactories.size(); i < count; i++) {
      Converter<ResponseBody, ?> converter =
      //在这里真正获取对应的Converter
          converterFactories.get(i).responseBodyConverter(type, annotations, this);
      if (converter != null) {
        //noinspection unchecked
        return (Converter<ResponseBody, T>) converter;
      }
    }

    StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
        .append(type)
        .append(".\n");
    if (skipPast != null) {
      builder.append("  Skipped:");
      for (int i = 0; i < start; i++) {
        builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
      }
      builder.append('\n');
    }
    builder.append("  Tried:");
    for (int i = start, count = converterFactories.size(); i < count; i++) {
      builder.append("\n   * ").append(converterFactories.get(i).getClass().getName());
    }
    throw new IllegalArgumentException(builder.toString());
  }

可以看出,如果返回为null,就会从下一个Converter.Factory中获取对应的Convert;如果没有添加Converter.Factory,就会只有一个默认的BuiltInConverters,并且只支持返回值为ResponseBodyVoid这2中类型或者注释中有Streaming的方法,否则会报错。

第五步:在Callback 接口中对转换后的对象进行处理

在前面的提到默认的CallAdapter.Factory 也就是在ExecutorCallAdapterFactory中其实有个细节没有细看:

 @Override public void enqueue(final Callback<T> callback) {
      if (callback == null) throw new NullPointerException("callback == null");

      delegate.enqueue(new Callback<T>() {
        @Override public void onResponse(Call<T> call, final Response<T> response) {
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              if (delegate.isCanceled()) {
                // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
                callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
              } else {
                callback.onResponse(ExecutorCallbackCall.this, response);
              }
            }
          });
        }

        @Override public void onFailure(Call<T> call, final Throwable t) {
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              callback.onFailure(ExecutorCallbackCall.this, t);
            }
          });
        }
      });
    }

我们往回看,看下callbackExecutor是什么

static class Android extends Platform {
    @Override public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }

    @Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
      return new ExecutorCallAdapterFactory(callbackExecutor);
    }

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

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

defaultCallbackExecutor其实就是把Runnable抛到主线程执行。
所以在我们的Callback中的onResponseonFailure 已经都是在主线程中执行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值