Retrofit2.5.0解析

Retrofit是非常知名的轮子了, 几年之前很火的就是Retrofit + Rxjava了.
相比单独的OkHttp,多了很多扩展. 能高度扩展, 我们想到的肯定是面向接口编程了.

网上的版本大多比较旧,下个最新版的看一下.基于最新版本2.5.0

1.基本用法

1.1 创建Retrofit对象,可以看到这里使用了builder模式

var commonClient = Retrofit.Builder()
        .baseUrl(NetWorkConstant.PORT_URL)
        .client(getHttpClient(COMMON_HEAD))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()

1.2 定义API接口,通过Retrofit对象创建并调用API

//定义API接口标准, 路径,入参, 回参
interface ApiService{
    @GET("restful/login")
    fun login(@QueryMap params: Map<String, String>): Flowable<ApiResponse<LoginResultDTO>>
}

//创建API实例
val apiService = NetworkManager.getCommonClient().create(ApiService::class.java);

//调用接口
apiService.login(params)

重点是第二步创建ApiService实例
val apiService = NetworkManager.getCommonClient().create(ApiService::class.java)
查看实现

  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 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的方法,直接反射调用
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            //如果是JDK8的default方法,直接反射调用default方法
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            //这里才是我们自己定义的方法被调用
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }

看到返回值是Proxy.newProxyInstance()动态代理把接口的方法转发给InvocationHandlerinvoke()方法内部调用.
可以看到Retrofit先处理了Object提供的方法和JDK8新增的default方法.都不是才执行这一行调用我们自己定义的业务方法.

return loadServiceMethod(method).invoke(args != null ? args : emptyArgs)

2. ServiceMethod

loadServiceMethod(method).invoke(args != null ? args : emptyArgs)分为两步

2.1 loadServiceMethod(method)

可以看到这里使用ConcurrentHashMap<Method,ServiceMethod>来缓存每个Method对应的SericeMethod对象.如果有缓存直接读取缓存,没有就调用ServiceMethod.parseAnnotations(this, method)创建新的SericeMethod

  //ConcurrentHashMap来缓存method, Concurrent包通过CAS解决线程情况下的资源竞争
  private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

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

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method); //有缓存就用缓存
      if (result == null) {  //没有缓存就根据当前method创建一个ServiceMethod对象,存入Map
        result = ServiceMethod.parseAnnotations(this, method);
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

2.2 ServiceMethod.parseAnnotations(this, method)

abstract class ServiceMethod<T> {
  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
    //1. 创建RequestFactory对象
    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) {  //返回是void也会抛出异常
      throw methodError(method, "Service methods cannot return void.");
    }
    //2. 交给他的子类HttpServiceMethod去实现
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

  abstract T invoke(Object[] args);
}
  1. RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method); 这里通过建造者模式构建了一个RequestFactory对象
final class RequestFactory {
  static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
    return new Builder(retrofit, method).build();
  }

  RequestFactory(Builder builder) {
    method = builder.method;    //方法
    baseUrl = builder.retrofit.baseUrl; //baseUrl
    httpMethod = builder.httpMethod;//POST,GET,DELETE...
    relativeUrl = builder.relativeUrl;// baseUrl+后缀
    headers = builder.headers; // http header
    contentType = builder.contentType; //http contentType
    hasBody = builder.hasBody; //POST请求使用
    isFormEncoded = builder.isFormEncoded; //application/x-www-form-urlencoded 是否默认转码
    isMultipart = builder.isMultipart; //标记是否是MultiPart上传文件
    parameterHandlers = builder.parameterHandlers; //重要参数
  }

  static final class Builder {
    Builder(Retrofit retrofit, Method method) {
      this.retrofit = retrofit;
      this.method = method;
      this.methodAnnotations = method.getAnnotations();
      this.parameterTypes = method.getGenericParameterTypes();
      this.parameterAnnotationsArray = method.getParameterAnnotations();
    }

    RequestFactory build() {
      .....
      return new RequestFactory(this);
    }
  }
}

parameterHandlers则负责解析 API 定义时每个方法的参数,并在构造 HTTP 请求时设置参数;

  1. 调用子类HttpServiceMethod的HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory)方法,传入第一步得到的requestFactory, 所以loadServiceMethod的真正工作是交给HttpServiceMethod来完成的.

3. HttpServiceMethod

查看类的注释: 把接口方法转换为 HTTP请求. 真正的转换工作是在这里进行的.

/** Adapts an invocation of an interface method into an HTTP call. */

查看parseAnnotations方法

  static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
      Retrofit retrofit, Method method, RequestFactory requestFactory) {
    //1. 创建CallAdapter
    CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);
    Type responseType = callAdapter.responseType();
    //设定的返回值类型不能是Retrofit和OKHttp内的Response.
    if (responseType == Response.class || responseType == okhttp3.Response.class) {
      throw methodError(method, "'"
          + Utils.getRawType(responseType).getName()
          + "' is not a valid response body type. Did you mean ResponseBody?");
    }
    //如果用Http的HEAD方法必须返回空
    if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
      throw methodError(method, "HEAD method must use Void as response type.");
    }
    //2. 创建responseConverter 
    Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);
    //3. 创建callFactory 
    okhttp3.Call.Factory callFactory = retrofit.callFactory;
    return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
  }

  private final RequestFactory requestFactory;
  private final okhttp3.Call.Factory callFactory;
  private final CallAdapter<ResponseT, ReturnT> callAdapter;
  private final Converter<ResponseBody, ResponseT> responseConverter;

  private HttpServiceMethod(RequestFactory requestFactory, okhttp3.Call.Factory callFactory,
      CallAdapter<ResponseT, ReturnT> callAdapter,
      Converter<ResponseBody, ResponseT> responseConverter) {
    this.requestFactory = requestFactory;
    this.callFactory = callFactory;
    this.callAdapter = callAdapter;
    this.responseConverter = responseConverter;
  }

可以看到,这里获取了三个对象callAdapter, responseConverter, callFactory并保存为成员变量.

  1. callFactory 负责创建 HTTP 请求,HTTP 请求被抽象为了 okhttp3.Call 类,它表示一个已经准备好,可以随时执行的 HTTP 请求;
  2. callAdapter 把 retrofit2.Call<T> 转为 T(注意和 okhttp3.Call 区分开来,retrofit2.Call<T> 表示的是对一个 Retrofit 方法的调用),这个过程会发送一个 HTTP 请求,拿到服务器返回的数据(通过 okhttp3.Call 实现),并把数据转换为声明的 T 类型对象(通过 Converter<F, T> 实现);
  3. responseConverter 是 Converter<ResponseBody, T> 类型,负责把服务器返回的数据(JSON、XML、二进制或者其他格式,由 ResponseBody 封装)转化为 T 类型的对象;

3.1 CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);

我们在构建Retrofit对象的时候会调用addCallAdapterFactory(RxJava2CallAdapterFactory.create()),这里用的是RxJava2CallAdapterFactory. 可以看到被添加到了内部的callAdapterFactories列表中

public final class Retrofit {
  //Retrofit内部维护了一个CallAdapter.Factory列表
  private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();

  public static final class Builder {
    private final Platform platform;
    private @Nullable okhttp3.Call.Factory callFactory;
    private @Nullable HttpUrl baseUrl;
    private final List<Converter.Factory> converterFactories = new ArrayList<>();
    private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
    private @Nullable Executor callbackExecutor;
    private boolean validateEagerly;
    
    // 我们指定的CallAdapter.Factory被添加到了列表中
    public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
      callAdapterFactories.add(checkNotNull(factory, "factory == null"));
      return this;
    }
  }
}

查看CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);方法

  private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
      Retrofit retrofit, Method method) {
    Type returnType = method.getGenericReturnType();
    Annotation[] annotations = method.getAnnotations();
    try {
      //noinspection unchecked
      //实际返回的是 retrofit.callAdapter(returnType, annotations);的结果
      return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
    } catch (RuntimeException e) { // Wide exception range because factories are user code.
      throw methodError(method, e, "Unable to create call adapter for %s", returnType);
    }
  }

查看retrofit.callAdapter(returnType, annotations);,调用了nextCallAdapter()方法.
可以看到这里通过遍历callAdapterFactories列表, 根据返回类型returnType和注解annotations来找到对应的CallAdapter.Factory.
举个例子: 如果返回值是Flowable或者Maybe,那么adapter肯定是RxJava2CallAdapterFactory而不是RxJavaCallAdapterFactory,因为这两个操作符在RxJava2中才被引入.

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

  public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
      Annotation[] annotations) {
    checkNotNull(returnType, "returnType == null");
    checkNotNull(annotations, "annotations == null");

    int start = callAdapterFactories.indexOf(skipPast) + 1;
    //遍历callAdapterFactories列表, 根据传入的returnType和annotations找到对应的CallAdapter.Factory, 这里也说明了一个Retrofit对象是支持多个CallAdapter.Factory的
    for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
      CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
      if (adapter != null) {
        return adapter;
      }
    }
   .....
  }

3.2 okhttp3.Call.Factory callFactory = retrofit.callFactory;

追踪retrofit.callFactory,发现在Retrofit对象build()的时候, 如果没有callFactory对象,就默认给一个callFactory = new OkHttpClient()
当然了,Retrofit.Builder也是提供了allFactory(okhttp3.Call.Factory factory)方法供我们自定义

public final class Retrofit {
  final okhttp3.Call.Factory callFactory;

  public static final class Builder {
    private @Nullable okhttp3.Call.Factory callFactory;

    Builder(Retrofit retrofit) {
      callFactory = retrofit.callFactory;
    }

    public Retrofit build() {
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        //如果没有传入callFactory,默认给一个OkHttpClient
        callFactory = new OkHttpClient();
      }
   }
   
   //Retrofit也支持传入自定义的okhttp3.Call.Factory
   public Builder callFactory(okhttp3.Call.Factory factory) {
      this.callFactory = checkNotNull(factory, "factory == null");
      return this;
   }
}

3.3 Converter<ResponseBody, ResponseT> responseConverter = createResponseConverter(retrofit, method, responseType);

和获取CallAdapter一样,调用的是Retrofit中的retrofit.responseBodyConverter方法

  Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);

  private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
      Retrofit retrofit, Method method, Type responseType) {
    Annotation[] annotations = method.getAnnotations();
    try {
      //和获取CallAdapter一样,调用的是Retrofit中的方法
      return retrofit.responseBodyConverter(responseType, annotations);
    } catch (RuntimeException e) { // Wide exception range because factories are user code.
      throw methodError(method, e, "Unable to create converter for %s", responseType);
    }
  }

查看retrofit.responseBodyConverter(responseType, annotations),逻辑和上面的retrofit.callAdapter(returnType, annotations)差不多,也是通过返回值和注解遍历Retrofit中的converterFactories列表查找合适的convertFactory

  public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
    return nextResponseBodyConverter(null, type, annotations);
  }

  public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
      @Nullable 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 =
          converterFactories.get(i).responseBodyConverter(type, annotations, this);
      if (converter != null) {
        //noinspection unchecked
        return (Converter<ResponseBody, T>) converter;
      }
    }
  }

3.4 invoke(args != null ? args : emptyArgs)

  @Override ReturnT invoke(Object[] args) {
    //真正发起HTTP call的流程,后面分析
    return callAdapter.adapt(
        new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
  }

requestFactory是父类ServiceMethod的包含了请求头,方法名,url等等信息.
CallAdapter,callFactory,responseConverter在Retrofit创建的时候就提供了,在前面三步做的只是根据返回值和注解查找的过程.

他们分别由okhttp3.Call.FactoryCallAdapter.FactoryConverter.Factory三个工厂提供. 工厂模块之间互不影响; 每个模块通过实现工厂接口也隐蔽了创建的细节.符合高内聚低耦合的标准

这些参数都是为了callAdapter.adapt( new OkHttpCall<>(requestFactory, args, callFactory, responseConverter))这一步发起HTTP call, 后面分析CallAdapter的时候会解释.

4. 模块的实现

4.1 CallAdapter.Factory

Retrofit内置了DefaultCallAdapterFactoryExecutorCallAdapterFactory两个实现.前者什么也不做,后者会将任务分发到Retforit.Builder().XXX...build()时传入的callbackExecutor来执行.

class Platform {
  List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
      @Nullable Executor callbackExecutor) {
    if (callbackExecutor != null) {  //如果指定了Executor,就交给他调度
      return singletonList(new ExecutorCallAdapterFactory(callbackExecutor));
    }   
    //默认的
    return singletonList(DefaultCallAdapterFactory.INSTANCE);
  }
}

以上两种的返回值都是retrofit2.Call.
通常Retrofit都是配合RxJava来使用的, 这时候我们用到了RxJava2CallAdapter来把retrofit2.Call转换为我们熟悉的Flowable,Observable等对象.

RxJavaCallAdapterFactory#get 方法中对返回值的类型进行了检查

if (rawType == Completable.class) {
  // Completable is not parameterized (which is what the rest of this method deals with) so it
  // can only be created with a single configuration.
  return new RxJava2CallAdapter(Void.class, scheduler, isAsync, false, true, false, false,
      false, true);
}

if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
   return null;
}
.... 
return new RxJava2CallAdapter(responseType, scheduler, isAsync, isResult, isBody, isFlowable,
        isSingle, isMaybe, false);

构造RxJava2CallAdapter对象

  RxJava2CallAdapter(Type responseType, @Nullable Scheduler scheduler, boolean isAsync,
      boolean isResult, boolean isBody, boolean isFlowable, boolean isSingle, boolean isMaybe,
      boolean isCompletable) {
    this.responseType = responseType;
    this.scheduler = scheduler;
    this.isAsync = isAsync;
    this.isResult = isResult;
    this.isBody = isBody;
    this.isFlowable = isFlowable;
    this.isSingle = isSingle;
    this.isMaybe = isMaybe;
    this.isCompletable = isCompletable;
  }

上面提到过HttpServiceMethod#invoke调用了callAdapter#adapt方法,我们关注下

@Override public Object adapt(Call<R> call) {
  // 这一步把我们原来的 Call 转换成了 Observable 对象
  Observable<Response<R>> responseObservable = isAsync
      ? new CallEnqueueObservable<>(call)  //加入队列
      : new CallExecuteObservable<>(call);   //马上执行
  Observable<?> observable;
  if (isResult) {
    observable = new ResultObservable<>(responseObservable);
  } else if (isBody) {
    observable = new BodyObservable<>(responseObservable);
  } else {
    observable = responseObservable;
  }
  //省略了Single,Flowable背压,Maybe等等处理
   .....
  return RxJavaPlugins.onAssembly(observable);
}

new CallEnqueueObservable<>(call)为例, 把传入的 retrofit2.Call 保存为originalCall

final class CallEnqueueObservable<T> extends Observable<Response<T>> {
  private final Call<T> originalCall;

  CallEnqueueObservable(Call<T> originalCall) {
    this.originalCall = originalCall;
  }
  
  //Observable定义的抽象方法,在Observable.subscribe()的时候会被调用
  @Override protected void subscribeActual(Observer<? super Response<T>> observer) {
    // Since Call is a one-shot type, clone it for each new observer.
    Call<T> call = originalCall.clone();
    CallCallback<T> callback = new CallCallback<>(call, observer);
    observer.onSubscribe(callback);
    if (!callback.isDisposed()) {
      call.enqueue(callback);
    }
  }
}

这里 retrofit2.Call 接口的实现是 OkHttpCall, 查看OkHttpCall#enqueue
,这里面也有一句call.enqueue,这里的call 是 okhttp3.Call,到这里,才是真正的把请求加入OkHttp的请求队列

final class OkHttpCall<T> implements Call<T> {
  @Override public void enqueue(final Callback<T> callback) {
    checkNotNull(callback, "callback == null");

    okhttp3.Call call;
    Throwable failure;
    //注意了,这里的call是okhttp3.Call对象
    call = rawCall = createRawCall();

     //这里用锁和executed 变量 控制线程竞争
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already executed.");
      executed = true;
      ....
    //okhttp3.Call.enqueue,加入OkHttp的请求队列
    call.enqueue(new okhttp3.Callback() {
      @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
        Response<T> response;
        try {
          response = parseResponse(rawResponse);
        } catch (Throwable e) {
          throwIfFatal(e);
          callFailure(e);
          return;
        }

        try {
          callback.onResponse(OkHttpCall.this, response); //成功响应
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      @Override public void onFailure(okhttp3.Call call, IOException e) {
        callFailure(e);
      }

      private void callFailure(Throwable e) {
        try {
          callback.onFailure(OkHttpCall.this, e); //失败的回调
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    });
  }
}

在Okhttp请求成功失败时,CallEnqueueObservable.CallCallback调用了Observable.onNext(), onComplete(), onError()方法.

final class CallEnqueueObservable<T> extends Observable<Response<T>>
  private static final class CallCallback<T> implements Disposable, Callback<T>
    @Override public void onResponse(Call<T> call, Response<T> response) {
      if (disposed) return;

      try {
        observer.onNext(response);

        if (!disposed) {
          terminated = true;
          observer.onComplete();
        }
      } catch (Throwable t) {
        if (terminated) {
          RxJavaPlugins.onError(t);
        } else if (!disposed) {
          try {
            observer.onError(t);
          } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaPlugins.onError(new CompositeException(t, inner));
          }
        }
      }
    }

    @Override public void onFailure(Call<T> call, Throwable t) {
      if (call.isCanceled()) return;

      try {
        observer.onError(t);
      } catch (Throwable inner) {
        Exceptions.throwIfFatal(inner);
        RxJavaPlugins.onError(new CompositeException(t, inner));
      }
    }
  }
}

这里有一段伪代码

Retrofit.Builder()
        .baseUrl(NetWorkConstant.PORT_URL)
        .client(getHttpClient(COMMON_HEAD))
         //RxJava2CallAdapterFactory把retrofit2.Call 转换成我们想要的Observable等RxJava里的对象
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()
        .create(ApiService::class.java)
        .login(params) //login方法执行完后,会发起okhttp3.Call.enqueue
        .subscribe({
            println("onNext")  //okhttp3.Callback的回调里会调用Observable.onNext, onError, onComplete
        },{
            println("onError")
        },{
            print("onComplete")
        })

4.2 okhttp3.Call.Factory

顾名思义,我们发起请求 okhttp3.Call call对象就是由他创建的.主要分为三个步骤.

final class OkHttpCall<T> implements retrofit2.Call<T> {
  private okhttp3.Call createRawCall() throws IOException {
    //调用okhttp3.Call.Factory创建okhttp3.Call
    okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
  }
}

//OkHttpClient实现了Call.Factory, 在newCallI()的实现里调用了RealCall.newRealCall()
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
  @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }
}

//真正创建了okhttp3.Call
final class RealCall implements Call
  static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    // Safely publish the Call instance to the EventListener.
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
  }
}

4.3 Converter.Factory

这里还是讨论常用的 GsonConverterFactory ,和 CallAdapterFactory 一样,实现接口就可以进行自定义. 以GsonConverterFactory为例

.addConverterFactory(GsonConverterFactory.create(gson))

创建 GsonConverterFactory

public final class GsonConverterFactory extends Converter.Factory {
  public static GsonConverterFactory create() {
    return create(new Gson());
  }

  public static GsonConverterFactory create(Gson gson) {
    if (gson == null) throw new NullPointerException("gson == null");
    return new GsonConverterFactory(gson);
  }

  private final Gson gson;

  private GsonConverterFactory(Gson gson) {
    this.gson = gson;
  }
}

在invoke方法时,通过returnType, annotations找到合适的 Converter

  //上面已经提到了, HttpServiceMethod里会调用这一句
  public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
    return nextResponseBodyConverter(null, type, annotations);
  }

  public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
      @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
    //遍历寻找Converter
    int start = converterFactories.indexOf(skipPast) + 1;
    for (int i = start, count = converterFactories.size(); i < count; i++) {
      Converter<ResponseBody, ?> converter =
          //调用Converter. responseBodyConverter()方法
          converterFactories.get(i).responseBodyConverter(type, annotations, this);
      if (converter != null) {
        //noinspection unchecked
        return (Converter<ResponseBody, T>) converter;
      }
    }
  }

调用GsonConverterFactory 创建 GsonResponseBodyConverter对象

public final class GsonConverterFactory extends Converter.Factory {
  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    //创建了GsonResponseBodyConverter对象
    return new GsonResponseBodyConverter<>(gson, adapter);
  }
}


final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
  private final Gson gson;
  private final TypeAdapter<T> adapter;

  GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
    this.gson = gson;
    this.adapter = adapter;
  }
  
  //接口里的convert 方法, 帮我们把value转换为我们想要的格式
  @Override public T convert(ResponseBody value) throws IOException {
    JsonReader jsonReader = gson.newJsonReader(value.charStream());
    try {
      T result = adapter.read(jsonReader);
      if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
        throw new JsonIOException("JSON document was not fully consumed.");
      }
      return result;
    } finally {
      value.close();
    }
  }
}

真正帮我们完成数据转json操作的是 GsonResponseBodyConverter.convert(ResponseBody value)方法,那么他在什么时候被调用呢?
在 okhttp3.Call 的onResponse()里, 会把okhttp3.Response解析成json

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

感谢

拆轮子系列:拆 Retrofit

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容

  • 目录介绍 1.首先回顾Retrofit简单使用方法 2.Retrofit的创建流程源码分析2.1 Retrofit...
    杨充211阅读 1,045评论 0 16
  • 并不想将Retrofit放在okhttp中,但是感觉单独出来太占地了,但是Retrofit中还是有使用到okhtt...
    taijielan阅读 451评论 0 0
  • 安卓开发领域中,很多重要的问题都有很好的开源解决方案,例如Square公司提供网络请求 OkHttp , Retr...
    aaron688阅读 1,901评论 1 20
  • 在开发Android APP时,肯定会使用到Http请求与服务器通信,上传或下载数据等功能。目前开源的Http请求...
    wangling90阅读 472评论 0 0
  • 今天听得到的罗辑思维:未来的知识服务什么样?非常受启发,也觉得得到这个模式非常有益。 能够迅速得到有效的知识,这个...
    康康1阅读 795评论 0 0