这篇文章上次修改于 2136 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

今天我们主要聊一聊 Retrofit 的源码,他是怎样对 OkHttp 包装的。

此次分析源码的版本 Retrofit 2.5.0

首先我们先了解一下 Retrofit 用法。

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();
         
GitHubService service = retrofit.create(GitHubService.class);

Call<List<Repo>> call = service.listRepos("octocat");

//发送网络请求(异步)
call.enqueue(new Callback<List<Repo>>() {
    @Override
    public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {

    }

    @Override
    public void onFailure(Call<List<Repo>> call, Throwable t) {

    }
});

// 发送网络请求(同步)
Response<List<Repo>> response = call.execute();

Retrofit 的 Builder 建造者模式

首先我们看到 Retrofit 的 Builder 建造者模式,

public Retrofit build() {
    // 配置 baseUrl
    if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
    }
    
    // 配置 OkHttpClient
    okhttp3.Call.Factory callFactory = this.callFactory;
    if (callFactory == null) {
        callFactory = new OkHttpClient();
    }

    // 执行 callback 的线程
    Executor callbackExecutor = this.callbackExecutor;
    if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
    }

    // Call 适配器,比如 RxJava、Java8 适配器
    List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
    callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

    // 数据转换器,比如 Gson、Jackson 等转换器
    List<Converter.Factory> converterFactories = new ArrayList<>(
      1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
        converterFactories.add(new BuiltInConverters());
        converterFactories.addAll(this.converterFactories);
        converterFactories.addAll(platform.defaultConverterFactories());

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

根据接口方法获取 Service

接下来我们再往下看 retrofit.create() 方法

public <T> T create(final Class<T> 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 (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            // 处理接口方法
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
    }

create() 本身就是一个动态代理。

调用 Service 的方法就会走动态代理

先看 loadServiceMethod() 方法,等会再看 invoke();

ServiceMethod<?> loadServiceMethod(Method method) {
    // 查询方法缓存
    ServiceMethod<?> result = serviceMethodCache.get(method);
    if (result != null) return result;
    
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        // 解析方法的注解以及返回类型确定各项参数以及 Call 适配器、数据转换器。
        result = ServiceMethod.parseAnnotations(this, method);
        serviceMethodCache.put(method, result);
      }
    }
    return result;
}

继续往下看 ServiceMethod.parseAnnotations() 方法。

static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
    // 解析方法的注解、参数注解、请求头等等,具体解析方式自己看 parseAnnotations() 方法的代码
    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) {
      throw methodError(method, "Service methods cannot return void.");
    }
    // 解析并创建 Call 适配器、数据转换器
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

继续查看 HttpServiceMethod.parseAnnotations() 方法。

static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
      Retrofit retrofit, Method method, RequestFactory requestFactory) {
    // 根据返回类型创建并获取 CallAdapter
    CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);
    Type responseType = callAdapter.responseType();
    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?");
    }
    if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
      throw methodError(method, "HEAD method must use Void as response type.");
    }
    
    // 根据 Response 类型创建并获取 Converter
    Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);

    okhttp3.Call.Factory callFactory = retrofit.callFactory;
    return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
}

继续回去看 invoke() 方法

@Override ReturnT invoke(Object[] args) {
    // 转换成相应的类型
    return callAdapter.adapt(
        new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}

// 以 Retrofit 默认适配器为例,假设 SDK version 小于 24
@Override public Call<Object> adapt(Call<Object> call) {
    return new ExecutorCallbackCall<>(callbackExecutor, call);
}

发送异步网络请求

@Override public void enqueue(final Callback<T> callback) {
      checkNotNull(callback, "callback == null");
      // 这里 delegate 是 OkHttpCall 对象
      // 大家可以自己看一看 OkHttpCall 的 enqueue() 方法,它本身就是对 okhttp3.Call 的包装。
      delegate.enqueue(new Callback<T>() {
        @Override public void onResponse(Call<T> call, final Response<T> response) {
          // callbackExecutor 最初配置的线程运行环境
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              if (delegate.isCanceled()) {
                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);
            }
          });
        }
      });
}

发送同步网络请求

@Override public Response<T> execute() throws IOException {
      // 这里 delegate 是 OkHttpCall 对象
      return delegate.execute();
}

总结

Retrofit 还是比较简单的,他就是对 OkHttp 的包装,还有很多细节,希望大家自己多去挖掘挖掘。