Retrofit源碼分析總結(jié)

1.簡(jiǎn)介

Retrofit是一個(gè)封裝了Okhttp網(wǎng)絡(luò)請(qǐng)求庫(kù)的優(yōu)秀框架,其可以輕松提供Restful風(fēng)格的接口。Retrofit官方地址

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

// 1.Retrofit構(gòu)建過(guò)程
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

// 2.創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口類(lèi)實(shí)例過(guò)程
GitHubService service = retrofit.create(GitHubService.class);

// 3.生成并執(zhí)行請(qǐng)求過(guò)程
Call<List<Repo>> repos = service.listRepos("octocat");
repos.execute() or repos.enqueue()
3.源碼分析

要想真正理解Retrofit內(nèi)部的核心源碼流程和設(shè)計(jì)思想,首先,需要對(duì)一下幾大設(shè)計(jì)模式有一定的了解:

1.Retrofit構(gòu)建過(guò)程 
建造者模式、工廠方法模式

2.創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口實(shí)例過(guò)程
外觀模式、代理模式、單例模式、策略模式、裝飾模式(建造者模式)

3.生成并執(zhí)行請(qǐng)求過(guò)程
適配器模式(代理模式、裝飾模式)

其次,需要對(duì)OKHttp源碼有一定的了解,如果不了解的可以看看這篇okhttp源碼分析總結(jié)。

源碼分析主要分為以下四步:

  1. 創(chuàng)建Retrofit實(shí)例
  2. 創(chuàng)建 網(wǎng)絡(luò)請(qǐng)求接口實(shí)例 并 配置網(wǎng)絡(luò)請(qǐng)求參數(shù)
  3. 發(fā)送網(wǎng)絡(luò)請(qǐng)求
  4. 處理服務(wù)器返回的數(shù)據(jù)
3.1 創(chuàng)建Retrofit實(shí)例

接下來(lái),我將按以下代碼順序?qū)?chuàng)建Retrofit實(shí)例進(jìn)行逐步分析


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

1. Retrofit

//關(guān)鍵的全局變量
public final class Retrofit {

    // 網(wǎng)絡(luò)請(qǐng)求配置對(duì)象(對(duì)網(wǎng)絡(luò)請(qǐng)求接口中方法注解進(jìn)行解析后得到的對(duì)象)
    // 作用:存儲(chǔ)網(wǎng)絡(luò)請(qǐng)求相關(guān)的配置,如網(wǎng)絡(luò)請(qǐng)求的方法、數(shù)據(jù)轉(zhuǎn)換器、網(wǎng)絡(luò)請(qǐng)求適配器、網(wǎng)絡(luò)請(qǐng)求工廠、基地址等
    private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
    ......
}

2. Retrofit#Builder

Retrofit使用了建造者模式通過(guò)內(nèi)部類(lèi)Builder類(lèi)建立一個(gè)Retrofit實(shí)例,如下:

public static final class Builder {

    // 平臺(tái)類(lèi)型對(duì)象(Platform -> Android)
    private final Platform platform;
    // 網(wǎng)絡(luò)請(qǐng)求工廠,默認(rèn)使用OkHttpCall(工廠方法模式)
    private @Nullable okhttp3.Call.Factory callFactory;
    // 網(wǎng)絡(luò)請(qǐng)求的url地址
    private @Nullable HttpUrl baseUrl;
    // 數(shù)據(jù)轉(zhuǎn)換器工廠的集合
    private final List<Converter.Factory> converterFactories = new ArrayList<>();
    // 網(wǎng)絡(luò)請(qǐng)求適配器工廠的集合,默認(rèn)是ExecutorCallAdapterFactory
    private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
    // 回調(diào)方法執(zhí)行器,在 Android 上默認(rèn)是封裝了 handler 的 MainThreadExecutor, 默認(rèn)作用是:切換線程(子線程 -> 主線程)
    private @Nullable Executor callbackExecutor;
    // 一個(gè)開(kāi)關(guān),為true則會(huì)緩存創(chuàng)建的ServiceMethod
    private boolean validateEagerly;
    
    
    //  Builder類(lèi)的構(gòu)造函數(shù)(有參)
    Builder(Platform platform) {
      // 接收Platform對(duì)象(Android平臺(tái))
      this.platform = platform;
      // BuiltInConverters是一個(gè)內(nèi)置的數(shù)據(jù)轉(zhuǎn)換器工廠(繼承Converter.Factory類(lèi))
      // new BuiltInConverters()是為了初始化數(shù)據(jù)轉(zhuǎn)換器
      converterFactories.add(new BuiltInConverters());
    }
    
    // Builder的構(gòu)造方法(無(wú)參)
    public Builder() {
      this(Platform.get());
    }
    
    ......
}

接下來(lái)看看Platform。
Platform是單例模式,通過(guò)Platform.get()來(lái)獲取對(duì)象。

class Platform {

    private static final Platform PLATFORM = findPlatform();

    static Platform get() {
      return PLATFORM;
    }

    private static Platform findPlatform() {
      try {
        // Class.forName(xxx.xx.xx)的作用:要求JVM查找并加載指定的類(lèi)(即JVM會(huì)執(zhí)行該類(lèi)的靜態(tài)代碼段)
        // 使用JVM加載類(lèi)的方式判斷是否是Android平臺(tái)
        Class.forName("android.os.Build");
        if (Build.VERSION.SDK_INT != 0) {
          return new Android();
        }
      } catch (ClassNotFoundException ignored) {
      }
      try {
        // 同時(shí)支持Java平臺(tái)
        Class.forName("java.util.Optional");
        return new Java8();
      } catch (ClassNotFoundException ignored) {
      }
      return new Platform();
    }

static class Android extends Platform {

    ...

    @Override public Executor defaultCallbackExecutor() {
        // 返回一個(gè)默認(rèn)的回調(diào)方法執(zhí)行器
        // 該執(zhí)行器作用:切換線程(子->>主線程),并在主線程(UI線程)中執(zhí)行回調(diào)方法
        return new MainThreadExecutor();
    }

    // 創(chuàng)建默認(rèn)的網(wǎng)絡(luò)請(qǐng)求適配器工廠,如果是Android7.0或Java8上,則使用了并發(fā)包中的CompletableFuture保證了回調(diào)的同步
    // 在Retrofit中提供了四種CallAdapterFactory(策略模式):
    // ExecutorCallAdapterFactory(默認(rèn))、GuavaCallAdapterFactory、va8CallAdapterFactory、RxJavaCallAdapterFactory
    
    @Override 
    List<? extends CallAdapter.Factory> 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<? extends Converter.Factory> defaultConverterFactories() {
      return Build.VERSION.SDK_INT >= 24
          ? singletonList(OptionalConverterFactory.INSTANCE)
          : Collections.<Converter.Factory>emptyList();
    }

    ...

    static class MainThreadExecutor implements Executor {

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

        @Override public void execute(Runnable r) {

            // 在UI線程對(duì)網(wǎng)絡(luò)請(qǐng)求返回?cái)?shù)據(jù)處理
            handler.post(r);
        }
    }
}

小結(jié):Builder設(shè)置了默認(rèn)的

  • 平臺(tái)類(lèi)型對(duì)象:Android
  • 網(wǎng)絡(luò)請(qǐng)求適配器工廠:CallAdapterFactory
  • 數(shù)據(jù)轉(zhuǎn)換器工廠: ConverterFactory
  • 回調(diào)執(zhí)行器:callbackExecutor

2. Retrofit#baseUrl(String baseUrl)

將String類(lèi)型的url轉(zhuǎn)換為OkHttp的HttpUrl過(guò)程如下:

public Builder baseUrl(String baseUrl) {
    // 把String類(lèi)型的url參數(shù)轉(zhuǎn)化為適合OKhttp的HttpUrl類(lèi)型
    HttpUrl httpUrl = HttpUrl.parse(baseUrl);     

    // 最終返回帶httpUrl類(lèi)型參數(shù)的baseUrl()
    // 下面繼續(xù)看baseUrl(httpUrl)
    return baseUrl(httpUrl);
    }


public Builder baseUrl(HttpUrl baseUrl) {
  //把URL參數(shù)分割成幾個(gè)路徑碎片
  List<String> pathSegments = baseUrl.pathSegments();   

  // 檢測(cè)最后一個(gè)碎片來(lái)檢查URL參數(shù)是不是以"/"結(jié)尾
  // 不是就拋出異常    
  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)

//將轉(zhuǎn)換工廠保存到converterFactories中,在構(gòu)造器中,已經(jīng)add了一個(gè)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;

    // 創(chuàng)建了一個(gè)含有Gson對(duì)象實(shí)例的GsonConverterFactory
    private GsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

小結(jié): 這一步是將一個(gè)含有Gson對(duì)象實(shí)例的GsonConverterFactory放入到了數(shù)據(jù)轉(zhuǎn)換器工廠converterFactories里。

如果要自定義Converter來(lái)實(shí)現(xiàn)請(qǐng)求結(jié)果轉(zhuǎn)化,按上面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) {
        // 默認(rèn)使用okhttp
         callFactory = new OkHttpClient();
    }

    Executor callbackExecutor = this.callbackExecutor;
    if (callbackExecutor == null) {
        // Android默認(rèn)的callbackExecutor
        callbackExecutor = platform.defaultCallbackExecutor();
    }

    // Make a defensive copy of the adapters and add the defaultCall adapter.
    List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
    // 添加默認(rèn)適配器工廠在集合尾部
    callAdapterFactories.addAll(platform.defaultCallAdapterFactorisca  llbackExecutor));

    // Make a defensive copy of the converters.
    List<Converter.Factory> converterFactories = new ArrayList<>(
        1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
  
    //BuiltInConverters添加到集合器的首位
    converterFactories.add(new BuiltInConverters());
    //步驟3插入了一個(gè)Gson的轉(zhuǎn)換器 - GsonConverterFactory(添加到集合器的第二位)
    converterFactories.addAll(this.converterFactories);
    // 添加默認(rèn)適配器工廠在集合尾部
    converterFactories.addAll(platform.defaultConverterFactories();

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

}

最終我們?cè)贐uilder類(lèi)中看到的6大核心對(duì)象都已經(jīng)配置到Retrofit對(duì)象中了。

3.2 創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口實(shí)例

Retrofit使用了外觀模式代理模式創(chuàng)建了網(wǎng)絡(luò)請(qǐng)求的接口實(shí)例,我們分析下create()方法。

public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
        // 判斷是否需要提前緩存ServiceMethod對(duì)象
        eagerlyValidateMethods(service);
    }

    // 該動(dòng)態(tài)代理是為了拿到網(wǎng)絡(luò)請(qǐng)求接口實(shí)例上所有注解
    // 使用動(dòng)態(tài)代理拿到請(qǐng)求接口所有注解配置后,創(chuàng)建網(wǎng)絡(luò)請(qǐng)求接口實(shí)例
    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對(duì)象加入LinkedHashMap<Method, ServiceMethod>集合
    // 使用LinkedHashMap集合的好處:lruEntries.values().iterator().next()獲取到的是集合最不經(jīng)常用到的元素,提供了一種Lru算法的實(shí)現(xiàn)
  }
}

繼續(xù)看看loadServiceMethod的內(nèi)部流程

ServiceMethod<?> loadServiceMethod(Method method) {

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

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      // 創(chuàng)建ServiceMethod對(duì)象前,先看serviceMethodCache有沒(méi)有緩存
      // 若沒(méi)緩存,則通過(guò)建造者模式創(chuàng)建 serviceMethod 對(duì)象
      if (result == null) {
            // 解析注解配置得到了ServiceMethod
            result = ServiceMethod.parseAnnotations(this, method);
            // 可以看到,最終加入到ConcurrentHashMap緩存中
            serviceMethodCache.put(method, result);
      }
    }
    return result;
}
abstract class ServiceMethod<T> {
  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method   method) {
        // 通過(guò)RequestFactory解析注解配置(工廠模式、內(nèi)部使用了建造者模式)
        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.");
        }

        // 最終是通過(guò)HttpServiceMethod構(gòu)建的請(qǐng)求方法
        return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
    }

    abstract T invoke(Object[] args);
}

接著看HttpServiceMethod.parseAnnotations()的內(nèi)部流程。

final class HttpServiceMethod<ResponseT, ReturnT> extends ServiceMethod<ReturnT> {

    static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
            Retrofit retrofit, Method method, RequestFactory requestFactory) {

        //根據(jù)網(wǎng)絡(luò)請(qǐng)求接口方法的返回值和注解類(lèi)型,從Retrofit對(duì)象中獲取對(duì)應(yīng)的網(wǎng)絡(luò)請(qǐng)求適配器
        CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);

        //異常判斷
        Type responseType = callAdapter.responseType();
        ...
      
        //根據(jù)網(wǎng)絡(luò)請(qǐng)求接口方法的返回值和注解類(lèi)型從Retrofit對(duì)象中獲取對(duì)應(yīng)的數(shù)據(jù)轉(zhuǎn)換器 
        Converter<ResponseBody, ResponseT> responseConverter =
                createResponseConverter(retrofit, method, responseType);

        okhttp3.Call.Factory callFactory = retrofit.callFactory;  //實(shí)際默認(rèn)創(chuàng)建一個(gè)new OkHttpClient()實(shí)例
        return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
    }
    ......

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

關(guān)注點(diǎn)1:createCallAdapter()

private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT>     createCallAdapter(
      Retrofit retrofit, Method method) {

    // 獲取網(wǎng)絡(luò)請(qǐng)求接口里方法的返回值類(lèi)型
    Type returnType = method.getGenericReturnType();

    // 獲取網(wǎng)絡(luò)請(qǐng)求接口接口里的注解
    Annotation[] annotations = method.getAnnotations();
    try {
      //noinspection unchecked
      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);
    }
}

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 <count; i++) {
        CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
        if (adapter != null) {
          return adapter;
        }
    }
}

關(guān)注點(diǎn)2:createResponseConverter()

private static <ResponseT> Converter<ResponseBody, ResponseT>  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 <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) {
...

int start = converterFactories.indexOf(skipPast) + 1;
// 遍歷 Converter.Factory 集合并尋找合適的工廠, 這里是GsonResponseBodyConverter
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;
  }
}

最終,執(zhí)行HttpServiceMethod的invoke方法

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

最終在adapt中創(chuàng)建了一個(gè)ExecutorCallbackCall對(duì)象,它是一個(gè)裝飾者,而在它內(nèi)部真正去執(zhí)行網(wǎng)絡(luò)請(qǐng)求的還是OkHttpCall。

3.3 執(zhí)行請(qǐng)求過(guò)程
Call<List<Repo>> repos = service.listRepos("octocat");
  • GitHubService對(duì)象實(shí)際上是動(dòng)態(tài)代理對(duì)象Proxy.newProxyInstance(),并不是真正的網(wǎng)絡(luò)請(qǐng)求接口創(chuàng)建的對(duì)象
  • 當(dāng)GitHubService對(duì)象調(diào)用listRepos()時(shí)會(huì)被動(dòng)態(tài)代理對(duì)象Proxy.newProxyInstance()攔截,然后調(diào)用自身的InvocationHandler # invoke()
  • invoke(Object proxy, Method method, Object... args)會(huì)傳入3個(gè)參數(shù):Object proxy:(代理對(duì)象)、Method method(listRepos())、Object...args(方法的參數(shù))
  • 接下來(lái)利用Java反射獲取到listRepos()的注解信息,配合args參數(shù)創(chuàng)建ServiceMethod對(duì)象。

OkHttpCall提供了兩種網(wǎng)絡(luò)請(qǐng)求方式:

  1. 同步請(qǐng)求:OkHttpCall.execute()
  2. 異步請(qǐng)求:OkHttpCall.enqueue()

repos.execute()

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

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

      ...

      call = rawCall;
      if (call == null) {
        try {
          // 創(chuàng)建一個(gè)OkHttp的Request對(duì)象請(qǐng)求
          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();
    }

    // 調(diào)用OkHttpCall的execute()發(fā)送網(wǎng)絡(luò)請(qǐng)求(同步),
    // 并解析網(wǎng)絡(luò)請(qǐng)求返回的數(shù)據(jù)
    return parseResponse(call.execute());
}


private okhttp3.Call createRawCall() throws IOException {
    // 創(chuàng)建 一個(gè)okhttp3.Request
    okhttp3.Call call =
    callFactory.newCall(requestFactory.create(args));
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
}


Response<T> 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();    

    // 根據(jù)響應(yīng)返回的狀態(tài)碼進(jìn)行處理    
    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 {
      // 將響應(yīng)體轉(zhuǎn)為Java對(duì)象
      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<T> callback) {

    // 使用靜態(tài)代理 delegate進(jìn)行異步請(qǐng)求 
    delegate.enqueue(new Callback<T>() {

      @Override 
      public void onResponse(Call<T> call, finalResponse<T>response) {
        // 線程切換,在主線程顯示結(jié)果
        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<T> call, final Throwable t) {
        callbackExecutor.execute(new Runnable() {
          @Override public void run() {
            callback.onFailure(ExecutorCallbackCall.this, t);
          }
        });
      }
    });
}

delegate.enqueue 內(nèi)部流程

@Override 
public void enqueue(final Callback<T> 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 {
          // 創(chuàng)建OkHttp的Request對(duì)象,再封裝成OkHttp.call
          // 方法同發(fā)送同步請(qǐng)求,此處上面已分析
          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<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();
          }
        }
  });
}

看到這里,已經(jīng)對(duì)Retrofit已經(jīng)有一個(gè)比較深入的了解。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容