Retrofit源码分析总结

1.简介

Retrofit是一个封装了Okhttp网络请求库的优秀框架,其可以轻松提供Restful风格的接口。Retrofit官方地址

2.基本用法
public interface GitHubService {
     @GET("users/{user}/repos")
     Call> listRepos(@Path("user") String user);
}

// 1.Retrofit构建过程
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

// 2.创建网络请求接口类实例过程
GitHubService service = retrofit.create(GitHubService.class);

// 3.生成并执行请求过程
Call> repos = service.listRepos("octocat");
repos.execute() or repos.enqueue()
3.源码分析

要想真正理解Retrofit内部的核心源码流程和设计思想,首先,需要对一下几大设计模式有一定的了解:

1.Retrofit构建过程 
建造者模式、工厂方法模式

2.创建网络请求接口实例过程
外观模式、代理模式、单例模式、策略模式、装饰模式(建造者模式)

3.生成并执行请求过程
适配器模式(代理模式、装饰模式)

其次,需要对OKHttp源码有一定的了解,如果不了解的可以看看这篇okhttp源码分析总结。

源码分析主要分为以下四步:

  1. 创建Retrofit实例
  2. 创建 网络请求接口实例 并 配置网络请求参数
  3. 发送网络请求
  4. 处理服务器返回的数据
3.1 创建Retrofit实例

接下来,我将按以下代码顺序对创建Retrofit实例进行逐步分析


Retrofit retrofit = new Retrofit.Builder()
                                 .baseUrl("https://api.github.com/")
                                 .addConverterFactory(GsonConverterFactory.create())
                                 .build();

1. Retrofit

//关键的全局变量
public final class Retrofit {

    // 网络请求配置对象(对网络请求接口中方法注解进行解析后得到的对象)
    // 作用:存储网络请求相关的配置,如网络请求的方法、数据转换器、网络请求适配器、网络请求工厂、基地址等
    private final Map> serviceMethodCache = new ConcurrentHashMap<>();
    ......
}

2. Retrofit#Builder

Retrofit使用了建造者模式通过内部类Builder类建立一个Retrofit实例,如下:

public static final class Builder {

    // 平台类型对象(Platform -> Android)
    private final Platform platform;
    // 网络请求工厂,默认使用OkHttpCall(工厂方法模式)
    private @Nullable okhttp3.Call.Factory callFactory;
    // 网络请求的url地址
    private @Nullable HttpUrl baseUrl;
    // 数据转换器工厂的集合
    private final List converterFactories = new ArrayList<>();
    // 网络请求适配器工厂的集合,默认是ExecutorCallAdapterFactory
    private final List callAdapterFactories = new ArrayList<>();
    // 回调方法执行器,在 Android 上默认是封装了 handler 的 MainThreadExecutor, 默认作用是:切换线程(子线程 -> 主线程)
    private @Nullable Executor callbackExecutor;
    // 一个开关,为true则会缓存创建的ServiceMethod
    private boolean validateEagerly;
    
    
    //  Builder类的构造函数(有参)
    Builder(Platform platform) {
      // 接收Platform对象(Android平台)
      this.platform = platform;
      // BuiltInConverters是一个内置的数据转换器工厂(继承Converter.Factory类)
      // new BuiltInConverters()是为了初始化数据转换器
      converterFactories.add(new BuiltInConverters());
    }
    
    // Builder的构造方法(无参)
    public Builder() {
      this(Platform.get());
    }
    
    ......
}

接下来看看Platform。
Platform是单例模式,通过Platform.get()来获取对象。

class Platform {

    private static final Platform PLATFORM = findPlatform();

    static Platform get() {
      return PLATFORM;
    }

    private static Platform findPlatform() {
      try {
        // Class.forName(xxx.xx.xx)的作用:要求JVM查找并加载指定的类(即JVM会执行该类的静态代码段)
        // 使用JVM加载类的方式判断是否是Android平台
        Class.forName("android.os.Build");
        if (Build.VERSION.SDK_INT != 0) {
          return new Android();
        }
      } catch (ClassNotFoundException ignored) {
      }
      try {
        // 同时支持Java平台
        Class.forName("java.util.Optional");
        return new Java8();
      } catch (ClassNotFoundException ignored) {
      }
      return new Platform();
    }

static class Android extends Platform {

    ...

    @Override public Executor defaultCallbackExecutor() {
        // 返回一个默认的回调方法执行器
        // 该执行器作用:切换线程(子->>主线程),并在主线程(UI线程)中执行回调方法
        return new MainThreadExecutor();
    }

    // 创建默认的网络请求适配器工厂,如果是Android7.0或Java8上,则使用了并发包中的CompletableFuture保证了回调的同步
    // 在Retrofit中提供了四种CallAdapterFactory(策略模式):
    // ExecutorCallAdapterFactory(默认)、GuavaCallAdapterFactory、va8CallAdapterFactory、RxJavaCallAdapterFactory
    
    @Override 
    List defaultCallAdapterFactories(
        @Nullable Executor callbackExecutor) {
      if (callbackExecutor == null) throw new AssertionError();
      ExecutorCallAdapterFactory executorFactory = new   ExecutorCallAdapterFactory(callbackExecutor);
      return Build.VERSION.SDK_INT >= 24
        ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
        : singletonList(executorFactory);
    }

    ...

    @Override 
    List defaultConverterFactories() {
      return Build.VERSION.SDK_INT >= 24
          ? singletonList(OptionalConverterFactory.INSTANCE)
          : Collections.emptyList();
    }

    ...

    static class MainThreadExecutor implements Executor {

        // 获取Android 主线程的Handler 
        private final Handler handler = new Handler(Looper.getMainLooper());

        @Override public void execute(Runnable r) {

            // 在UI线程对网络请求返回数据处理
            handler.post(r);
        }
    }
}

小结:Builder设置了默认的

  • 平台类型对象:Android
  • 网络请求适配器工厂:CallAdapterFactory
  • 数据转换器工厂: ConverterFactory
  • 回调执行器:callbackExecutor

2. Retrofit#baseUrl(String baseUrl)

将String类型的url转换为OkHttp的HttpUrl过程如下:

public Builder baseUrl(String baseUrl) {
    // 把String类型的url参数转化为适合OKhttp的HttpUrl类型
    HttpUrl httpUrl = HttpUrl.parse(baseUrl);     

    // 最终返回带httpUrl类型参数的baseUrl()
    // 下面继续看baseUrl(httpUrl)
    return baseUrl(httpUrl);
    }


public Builder baseUrl(HttpUrl baseUrl) {
  //把URL参数分割成几个路径碎片
  List pathSegments = baseUrl.pathSegments();   

  // 检测最后一个碎片来检查URL参数是不是以"/"结尾
  // 不是就抛出异常    
  if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
    throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
  }     
  this.baseUrl = baseUrl;
  return this;
}

3. Retrofit#addConverterFactory(Converter.Factory factory)

//将转换工厂保存到converterFactories中,在构造器中,已经add了一个BuiltInConverters
public Builder addConverterFactory(Converter.Factory factory) {
  converterFactories.add(checkNotNull(factory, "factory == null"));
  return this;
}

再看GsonConverterFactory.creat()

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;

    // 创建了一个含有Gson对象实例的GsonConverterFactory
    private GsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

小结: 这一步是将一个含有Gson对象实例的GsonConverterFactory放入到了数据转换器工厂converterFactories里。

如果要自定义Converter来实现请求结果转化,按上面GsonConverterFactory那样就可以了,使用工厂方法模式

4. Retrofit#build()

public Retrofit build() {

    if (baseUrl == null) {
      throw new IllegalStateException("Base URL required.");
    }

    okhttp3.Call.Factory callFactory = this.callFactory;
    if (callFactory == null) {
        // 默认使用okhttp
         callFactory = new OkHttpClient();
    }

    Executor callbackExecutor = this.callbackExecutor;
    if (callbackExecutor == null) {
        // Android默认的callbackExecutor
        callbackExecutor = platform.defaultCallbackExecutor();
    }

    // Make a defensive copy of the adapters and add the defaultCall adapter.
    List callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
    // 添加默认适配器工厂在集合尾部
    callAdapterFactories.addAll(platform.defaultCallAdapterFactorisca  llbackExecutor));

    // Make a defensive copy of the converters.
    List converterFactories = new ArrayList<>(
        1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
  
    //BuiltInConverters添加到集合器的首位
    converterFactories.add(new BuiltInConverters());
    //步骤3插入了一个Gson的转换器 - GsonConverterFactory(添加到集合器的第二位)
    converterFactories.addAll(this.converterFactories);
    // 添加默认适配器工厂在集合尾部
    converterFactories.addAll(platform.defaultConverterFactories();

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

}

最终我们在Builder类中看到的6大核心对象都已经配置到Retrofit对象中了。

3.2 创建网络请求接口实例

Retrofit使用了外观模式代理模式创建了网络请求的接口实例,我们分析下create()方法。

public  T create(final Class service) {
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
        // 判断是否需要提前缓存ServiceMethod对象
        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.
            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);
          }
    });
 }

private void eagerlyValidateMethods(Class service) {

  Platform platform = Platform.get();
  for (Method method : service.getDeclaredMethods()) {
    if (!platform.isDefaultMethod(method)) {
      loadServiceMethod(method);
    }
    // 将传入的ServiceMethod对象加入LinkedHashMap集合
    // 使用LinkedHashMap集合的好处:lruEntries.values().iterator().next()获取到的是集合最不经常用到的元素,提供了一种Lru算法的实现
  }
}

继续看看loadServiceMethod的内部流程

ServiceMethod loadServiceMethod(Method method) {

    ServiceMethod result = serviceMethodCache.get(method);
    if (result != null) return result;

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      // 创建ServiceMethod对象前,先看serviceMethodCache有没有缓存
      // 若没缓存,则通过建造者模式创建 serviceMethod 对象
      if (result == null) {
            // 解析注解配置得到了ServiceMethod
            result = ServiceMethod.parseAnnotations(this, method);
            // 可以看到,最终加入到ConcurrentHashMap缓存中
            serviceMethodCache.put(method, result);
      }
    }
    return result;
}
abstract class ServiceMethod {
  static  ServiceMethod parseAnnotations(Retrofit retrofit, Method   method) {
        // 通过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) {
          throw methodError(method, "Service methods cannot return void.");
        }

        // 最终是通过HttpServiceMethod构建的请求方法
        return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
    }

    abstract T invoke(Object[] args);
}

接着看HttpServiceMethod.parseAnnotations()的内部流程。

final class HttpServiceMethod extends ServiceMethod {

    static  HttpServiceMethod parseAnnotations(
            Retrofit retrofit, Method method, RequestFactory requestFactory) {

        //根据网络请求接口方法的返回值和注解类型,从Retrofit对象中获取对应的网络请求适配器
        CallAdapter callAdapter = createCallAdapter(retrofit, method);

        //异常判断
        Type responseType = callAdapter.responseType();
        ...
      
        //根据网络请求接口方法的返回值和注解类型从Retrofit对象中获取对应的数据转换器 
        Converter responseConverter =
                createResponseConverter(retrofit, method, responseType);

        okhttp3.Call.Factory callFactory = retrofit.callFactory;  //实际默认创建一个new OkHttpClient()实例
        return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
    }
    ......

    //callAdapter.adapt() 返回的就是Call对象。
    @Override ReturnT invoke(Object[] args) {
        return callAdapter.adapt(
                new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
    }
}

关注点1:createCallAdapter()

private static  CallAdapter     createCallAdapter(
      Retrofit retrofit, Method method) {

    // 获取网络请求接口里方法的返回值类型
    Type returnType = method.getGenericReturnType();

    // 获取网络请求接口接口里的注解
    Annotation[] annotations = method.getAnnotations();
    try {
      //noinspection unchecked
      return (CallAdapter)  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);
    }
}

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

public CallAdapter nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
  Annotation[] annotations) {
    ...

    int start = callAdapterFactories.indexOf(skipPast) + 1;
    // 遍历 CallAdapter.Factory 集合寻找合适的工厂
    for (int i = start, count = callAdapterFactories.size(); i  adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
        if (adapter != null) {
          return adapter;
        }
    }
}

关注点2:createResponseConverter()

private static  Converter  createResponseConverter(
     Retrofit retrofit, Method method, Type responseType) {
   Annotation[] annotations = method.getAnnotations();
   try {
     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);
   }
}

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

public  Converter nextResponseBodyConverter(
  @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
...

int start = converterFactories.indexOf(skipPast) + 1;
// 遍历 Converter.Factory 集合并寻找合适的工厂, 这里是GsonResponseBodyConverter
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;
  }
}

最终,执行HttpServiceMethod的invoke方法

//callAdapter.adapt() 返回的就是Call对象。
@Override ReturnT invoke(Object[] args) {
    return callAdapter.adapt(
            new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}

最终在adapt中创建了一个ExecutorCallbackCall对象,它是一个装饰者,而在它内部真正去执行网络请求的还是OkHttpCall。

3.3 执行请求过程
Call> repos = service.listRepos("octocat");
  • GitHubService对象实际上是动态代理对象Proxy.newProxyInstance(),并不是真正的网络请求接口创建的对象
  • 当GitHubService对象调用listRepos()时会被动态代理对象Proxy.newProxyInstance()拦截,然后调用自身的InvocationHandler # invoke()
  • invoke(Object proxy, Method method, Object... args)会传入3个参数:Object proxy:(代理对象)、Method method(listRepos())、Object...args(方法的参数)
  • 接下来利用Java反射获取到listRepos()的注解信息,配合args参数创建ServiceMethod对象。

OkHttpCall提供了两种网络请求方式:

  1. 同步请求:OkHttpCall.execute()
  2. 异步请求:OkHttpCall.enqueue()

repos.execute()

@Override public Response execute() throws IOException {
    okhttp3.Call call;

    synchronized (this) {
      if (executed) throw new IllegalStateException("Already executed.");
      executed = true;

      ...

      call = rawCall;
      if (call == null) {
        try {
          // 创建一个OkHttp的Request对象请求
          call = rawCall = createRawCall();
        } catch (IOException | RuntimeException | Error e) {
          throwIfFatal(e); //  Do not assign a fatal error to     creationFailure.
          creationFailure = e;
          throw e;
        }
      }
    }

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

    // 调用OkHttpCall的execute()发送网络请求(同步),
    // 并解析网络请求返回的数据
    return parseResponse(call.execute());
}


private okhttp3.Call createRawCall() throws IOException {
    // 创建 一个okhttp3.Request
    okhttp3.Call call =
    callFactory.newCall(requestFactory.create(args));
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
}


Response parseResponse(okhttp3.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body(); 

    // Remove the body's source (the only stateful object) so we can   pass the response along.
    rawResponse = rawResponse.newBuilder()
        .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
        .build();    

    // 根据响应返回的状态码进行处理    
    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
      try {
        // Buffer the entire body to avoid future I/O.
        ResponseBody bufferedBody = Utils.buffer(rawBody);
        return Response.error(bufferedBody, rawResponse);
      } finally {
        rawBody.close();
      }
    }    
    if (code == 204 || code == 205) {
      rawBody.close();
      return Response.success(null, rawResponse);
    }    


    ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
    try {
      // 将响应体转为Java对象
      T body = responseConverter.convert(catchingBody);

      return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
      // If the underlying source threw an exception, propagate that     rather than indicating it was
      // a runtime exception.
      catchingBody.throwIfCaught();
      throw e;
    }
}

reponse.enqueque

@Override 
public void enqueue(final Callback callback) {

    // 使用静态代理 delegate进行异步请求 
    delegate.enqueue(new Callback() {

      @Override 
      public void onResponse(Call call, finalResponseresponse) {
        // 线程切换,在主线程显示结果
        callbackExecutor.execute(new Runnable() {
            @Override 
             public void run() {
            if (delegate.isCanceled()) {
              callback.onFailure(ExecutorCallbackCall.this, newIOException("Canceled"));
            } else {
              callback.onResponse(ExecutorCallbackCall.this,respons);
            }
          }
        });
      }
      @Override 
      public void onFailure(Call call, final Throwable t) {
        callbackExecutor.execute(new Runnable() {
          @Override public void run() {
            callback.onFailure(ExecutorCallbackCall.this, t);
          }
        });
      }
    });
}

delegate.enqueue 内部流程

@Override 
public void enqueue(final Callback callback) {
    checkNotNull(callback, "callback == null");

    okhttp3.Call call;
    Throwable failure;

    synchronized (this) {
      if (executed) throw new IllegalStateException("Already executed.");
      executed = true;

      call = rawCall;
      failure = creationFailure;
      if (call == null && failure == null) {
        try {
          // 创建OkHttp的Request对象,再封装成OkHttp.call
          // 方法同发送同步请求,此处上面已分析
          call = rawCall = createRawCall(); 
        } catch (Throwable t) {
          failure = creationFailure = t;
        }
      }

    call.enqueue(new okhttp3.Callback() {
        @Override 
        public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
          Response 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();
          }
        }
  });
}

看到这里,已经对Retrofit已经有一个比较深入的了解。

你可能感兴趣的:(Retrofit源码分析总结)