Retrofit 源碼簡單分析

眾所周知,在現(xiàn)在的Android開發(fā)中,針對與網(wǎng)絡(luò)請求,Retrofit+okHttp的組合絕對是不二之選,而在網(wǎng)上針對于Retrofit分析的文章也有很多了,這次我也分享一些閱讀Retrofit源碼的心得,希望能夠?qū)Υ蠹矣兴鶐椭S捎谖以诠ぷ髦惺褂玫陌姹緸?.1,所以本次也是針對2.1版本進(jìn)行分析,首先來看看Retrofit一種簡單的用法:

Retrofit簡單使用示例

首先創(chuàng)建出Retrofit對象,進(jìn)行相應(yīng)的初始化配置:

    retrofit=new Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .client(getClient())
        .build();

然后在Service接口中寫入相應(yīng)方法,并加上相應(yīng)的注解:

    public interface Api {
        @GET(apiUrl)
        Call<Response> methodName();
    }

最后傳入請求的回調(diào)方法Callback就完成了:

    retrofit.create(Api.class).methodName().enqueue(Callback);

對于Retrofit對象的Build中,主要的都是對于參數(shù)的初始化,所以本次就從Retrofit類中的create(final Class<T> service)入手

Retrofit.create

public <T> T create(final Class<T> service) {
    //api類必須為接口,且不能實(shí)現(xiàn)或繼承其他接口,否則在動態(tài)代理步驟將會拋出異常
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
        //立即開始遍歷調(diào)用service中的所有方法
        eagerlyValidateMethods(service);
    }
    //返回service類的動態(tài)代理對象,當(dāng)調(diào)用service中的方法時,就會進(jìn)入其中進(jìn)行處理
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          //獲取當(dāng)前平臺(Android或Java8)
          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.
            // 如果該方法為Class類中的方法,則直接執(zhí)行
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            //判斷給方法是否為default method,針對Android平臺,該值永遠(yuǎn)為false,所以不應(yīng)在Service類中加入default方法,經(jīng)嘗試可能會導(dǎo)致崩潰
            //關(guān)于default method可以參考 http://ebnbin.com/2015/12/20/java-8-default-methods/
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            //1.獲取調(diào)用方法的ServiceMethod對象
            ServiceMethod serviceMethod = loadServiceMethod(method);
            //2.創(chuàng)建OkHttpCall對象
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            //3.將上一步生成的OkHttpCall對象轉(zhuǎn)換為在service中所配置的Call對象
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
 }

在這段代碼的最后所返回的Call對象就是用來使用的Call對象了。

其中有一個很有趣的地方,在 Platform 類中有一個通過判斷特定的類是否存在的方式獲取當(dāng)前平臺的步驟,在我的2.1版本中有這么一段代碼:

try {
    Class.forName("org.robovm.apple.foundation.NSObject");
    return new IOS();
} catch (ClassNotFoundException ignored) {}

但在最新的2.3版本中這段代碼已被移除,這說明Retrofit在之前版本中有對IOS平臺的支持,但是我在網(wǎng)上卻沒有找到相關(guān)的資料,不知道有沒有哪位朋友能為我解答一下。

在上面的代碼中,重點(diǎn)是最后的三行代碼,下面就分別對于這三行代碼進(jìn)分析:

1.ServiceMethod serviceMethod = loadServiceMethod(method);

Retrofit.loadServiceMethod

下面來通過loadServiceMethod方法看看ServiceMethod對象是如何創(chuàng)建出來的

  ServiceMethod loadServiceMethod(Method method) {
    ServiceMethod result;
    synchronized (serviceMethodCache) {
      //該方法的ServiceMethod對象是否已存在緩存中,如果是,則直接使用緩存中的對象
      result = serviceMethodCache.get(method);
      if (result == null) {
        //創(chuàng)建ServiceMethod對象并將其放入緩存
        result = new ServiceMethod.Builder(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

在代碼中可以看出創(chuàng)建ServiceMethod對象主要都在ServiceMethod.Builder之中

在其中我發(fā)現(xiàn)了一點(diǎn),在我所使用的2.1版本中,作為緩存使用的serviceMethodCache為LinkedHashMap,但在最新的2.3版本中已被換成了線程安全的ConcurrentHashMap。

ServiceMethod.Builder.Builder

首先看看Build中的構(gòu)造方法:

    public Builder(Retrofit retrofit, Method method) {
      this.retrofit = retrofit;  //retrofit對象
      this.method = method;  //所調(diào)用的方法
      this.methodAnnotations = method.getAnnotations();  //方法上的注解
      this.parameterTypes = method.getGenericParameterTypes();  //方法中參數(shù)的類型
      this.parameterAnnotationsArray = method.getParameterAnnotations();  //方法中參數(shù)上的注解
    }

可以看出,構(gòu)造方法中的代碼很簡單,就是針對各個變量的賦值操作。下面就是ServiceMethod中的重頭戲,也就是build方法,對于注解的解析也都是在這里完成的,這一部分的代碼雖多,但是大部分都是對于注解的解析與異常的判斷,還是一樣先來看看代碼:

ServiceMethod.Builder.build

    public ServiceMethod build() {
      //代碼中將略去其中的合法性檢測部分
    
      //通過retrofit中的CallAdapterFactory生成CallAdapter,用以生成網(wǎng)絡(luò)請求所需的執(zhí)行器
      callAdapter = createCallAdapter();
      //數(shù)據(jù)數(shù)據(jù)轉(zhuǎn)換工廠,例如常用的GsonConverterFactory
      responseConverter = createResponseConverter();

      //解析方法上的注解
      for (Annotation annotation : methodAnnotations) {
        parseMethodAnnotation(annotation);
      }

      //解析方法中各參數(shù)上的注解
      int parameterCount = parameterAnnotationsArray.length;
      parameterHandlers = new ParameterHandler<?>[parameterCount];
      for (int p = 0; p < parameterCount; p++) {
        Type parameterType = parameterTypes[p];

        Annotation[] parameterAnnotations = parameterAnnotationsArray[p];

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

      //返回ServiceMethod對象
      return new ServiceMethod<>(this);
    }

其中最重要的應(yīng)該是屬于對于方法與參數(shù)的注解解析的部分了,這也是Retrofit的特色之一,先來看看對于方法部分的注解解析:

ServiceMethod.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);
      } 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();
        headers = parseHeaders(headersToParse);
      } else if (annotation instanceof Multipart) {
        isMultipart = true;
      } else if (annotation instanceof FormUrlEncoded) {
        isFormEncoded = true;
      }
    }

可以看出來,這個方法中的邏輯很簡單,主要是判斷出注解的類型,并將對應(yīng)的字符串傳入之后的處理中,真正的處理還是在parseHttpMethodAndPath與parseHeaders兩個方法中

ServiceMethod.parseHttpMethodAndPath

    private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
      //除去異常判斷后的代碼
      
      //方法的類型(如GET,POST,PUT等)
      this.httpMethod = httpMethod;
      //是否含有Body
      this.hasBody = hasBody;

      //判斷相對路徑是否為空
      if (value.isEmpty()) {
        return;
      }

      //將相對路徑
      this.relativeUrl = value;
      //解析相對路徑中的參數(shù)
      this.relativeUrlParamNames = parsePathParameters(value);
    }

在除去其中異常判斷后,這個方法的邏輯就變得非常清晰了

ServiceMethod.parsePathParameters

  static Set<String> parsePathParameters(String path) {
    // PARAM_URL_REGEX = \{([a-zA-Z][a-zA-Z0-9_-]*)\}
    Matcher m = PARAM_URL_REGEX.matcher(path);
    Set<String> patterns = new LinkedHashSet<>();
    while (m.find()) {
      patterns.add(m.group(1));
    }
    return patterns;
  }

這個方法也很好理解,使用正則表達(dá)式匹配出相對路徑中以"{}"包裹的變量,然后放入Set集合中

ServiceMethod.parseHeaders

該方法的作用為Header注解的解析:

    private Headers parseHeaders(String[] headers) {
      Headers.Builder builder = new Headers.Builder();
      for (String header : headers) {
        //解析出header中的key和value
        int colon = header.indexOf(':');
        String headerName = header.substring(0, colon);
        String headerValue = header.substring(colon + 1).trim();
        //針對Content-type的頭,將其存入contentType變量中
        if ("Content-Type".equalsIgnoreCase(headerName)) {
          MediaType type = MediaType.parse(headerValue);
          contentType = type;
        } else {
          builder.add(headerName, headerValue);
        }
      }
      //創(chuàng)建Headers對象
      return builder.build();
    }

ServiceMethod.parseParameterAnnotation

這個方法用于參數(shù)注解的解析

    private ParameterHandler<?> parseParameterAnnotation(
        int p, Type type, Annotation[] annotations, Annotation annotation) {
      if (annotation instanceof Url) {
        //do something
      } else if (annotation instanceof Path) {
        //do something
      } else if (annotation instanceof Query) {
        //do something
      } else if (annotation instanceof QueryMap) {
       //do something
      } else if (annotation instanceof Header) {
        //do something
      } else if (annotation instanceof HeaderMap) {
        //do something
      } else if (annotation instanceof Field) {
        //do something
      } else if (annotation instanceof FieldMap) {
        //do something
      } else if (annotation instanceof Part) {
        //do something
      } else if (annotation instanceof PartMap) {
        gotPart = true;
        //do something
      } else if (annotation instanceof Body) {
        //do something
      }

      return null; // Not a Retrofit annotation.
    }

parseParameterAnnotation這個方法中的代碼雖然多,但是在簡化之后可以看出來,就是針對不同的參數(shù)類型進(jìn)行不同的處理然后返回相應(yīng)的ParameterHandler對象,因?yàn)槠渲嗅槍Ω鱾€類型參數(shù)的處理比較繁瑣,就不一一列舉了。

需要提到的是,在這個方法中,有一個類的出現(xiàn)頻率非常的高,這就是ParameterHandler類,這個類的主要作用是將注解中的各項(xiàng)參數(shù)通過RequestBuilder類轉(zhuǎn)換為okHttp中使用的Request。

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

在OkHttpCall類中,最主要的就是execute與enqueue兩個方法,分別為同步與異步的網(wǎng)絡(luò)請求,但是需要注意的是,這兩個方法并不是我們在使用中所調(diào)用的方法,真正提供給外界調(diào)用的方法,會在文章之后的部分講到。

OkHttpCall.execute

  @Override public Response<T> execute() throws IOException {
    //okHttp中的call對象,由于本次分析限于Retrofit中,所以不做深究
    okhttp3.Call call;

    synchronized (this) {
      //一個OkhttpCall對象只能執(zhí)行一次網(wǎng)絡(luò)請求
      if (executed) throw new IllegalStateException("Already executed.");
      executed = true;

      //省略部分異常判斷代碼

      call = rawCall;
      if (call == null) {
        try {
          //如果okHttp對象未創(chuàng)建,則在創(chuàng)建后賦值給變量call
          call = rawCall = createRawCall();
        } catch (IOException | RuntimeException e) {
          creationFailure = e;
          throw e;
        }
      }
    }

    //防止當(dāng)調(diào)用過cancel方法后新創(chuàng)建的Call未被cancel的情況
    if (canceled) {
      call.cancel();
    }

    //使用okhttp開始執(zhí)行網(wǎng)絡(luò)請求
    return parseResponse(call.execute());
  }

OkHttpCall.enqueue

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

    //okHttp中的call對象,由于本次分析限于Retrofit中,所以不做深究
    okhttp3.Call call;
    Throwable failure;

    //一個OkhttpCall對象只能執(zhí)行一次網(wǎng)絡(luò)請求
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already executed.");
      executed = true;

      call = rawCall;
      failure = creationFailure;
      if (call == null && failure == null) {
        try {
          //如果okHttp對象未創(chuàng)建,則在創(chuàng)建后賦值給變量call
          call = rawCall = createRawCall();
        } catch (Throwable t) {
          failure = creationFailure = t;
        }
      }
    }

    //創(chuàng)建okhttp對象失敗時,直接進(jìn)行Fail的回調(diào)方法
    if (failure != null) {
      callback.onFailure(this, failure);
      return;
    }

    //防止當(dāng)調(diào)用過cancel方法后新創(chuàng)建的Call未被cancel的情況
    if (canceled) {
      call.cancel();
    }

    //使用okhttp開始執(zhí)行網(wǎng)絡(luò)請求,并針對返回結(jié)果調(diào)用Callback中相應(yīng)的回調(diào)方法
    call.enqueue(new okhttp3.Callback() {
      @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
          throws IOException {
        Response<T> response;
        try {
          response = parseResponse(rawResponse);
        } catch (Throwable e) {
          callFailure(e);
          return;
        }
        callSuccess(response);
      }

      @Override public void onFailure(okhttp3.Call call, IOException e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callFailure(Throwable e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callSuccess(Response<T> response) {
        try {
          callback.onResponse(OkHttpCall.this, response);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    });
  }

enqueue方法在主要的邏輯上,與上面的execute是基本相同的,但是有一點(diǎn)需要注意,就是當(dāng)收到Response時并不會馬上進(jìn)行Callback中的onResponse回調(diào),而是會調(diào)用parseResponse方法對返回的Response進(jìn)行一次解析,如果解析中出現(xiàn)了異常,依然會進(jìn)行onFailure的回調(diào)方法。

OkHttpCall.parseResponse

  Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
    // 取出Response中的Body
    ResponseBody rawBody = rawResponse.body();

    // 這個變量就是最后獲得的Response中的rawResponse,這實(shí)際上是一個在請求中返回的,去除了body部分的okhttp.Response原始對象
    // 移除okhttp3.Response中的Source部分并重建一個okhttp.Response對象
    // 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();
    //如果code不在200~299的范圍內(nèi),則代表請求異常
    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();
      }
    }

    // 204 NO CONTENT 與 205 RESET CONTENT 兩個code是不含有body的
    // 具體可以查閱https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204與
    //           https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/205
    if (code == 204 || code == 205) {
      return Response.success(null, rawResponse);
    }

    // ExceptionCatchingRequestBody是為了捕獲在解析rawBody中的內(nèi)容的buffer時拋出的異常
    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
      // 通過Converter(如:GsonResponseBodyConverter)將Response中的流解析為所需的返回類型
      T body = serviceMethod.toResponse(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;
    }
  }

這個方法主要是對okhttp中返回的response進(jìn)行一次解析,對其進(jìn)行一些預(yù)處理,并將其轉(zhuǎn)換為更易于使用的Response對象

OkHttpCall.createRawCall

  private okhttp3.Call createRawCall() throws IOException {
    //獲取ServiceMethod生成的Request對象
    Request request = serviceMethod.toRequest(args);
    //通過callFactory將Request轉(zhuǎn)換為Okhttp3.Call
    okhttp3.Call call = serviceMethod.callFactory.newCall(request);
    if (call == null) {
      throw new NullPointerException("Call.Factory returned null.");
    }
    return call;
  }

這個方法主要用于創(chuàng)建okHttp中的Call對象,邏輯非常簡單,就不多做分析了

3.serviceMethod.callAdapter.adapt(okHttpCall)

這個方法實(shí)際是使用在創(chuàng)建Retrofit對象時傳入的CallAdapterFactory將OkHttpCall對象轉(zhuǎn)換為最后使用所需的對象,Retrofit中會默認(rèn)配置一個ExecutorCallAdapterFactory,除此之外還有常用的RxJavaCallAdapterFactory與一個最簡單的DefaultCallAdapterFactory。我們抽取出其中的adapt方法來看一看:

DefaultCallAdapterFactory

final class DefaultCallAdapterFactory extends CallAdapter.Factory {
  //DefaultCallAdapterFactory在返回時為一個單例對象
  static final CallAdapter.Factory INSTANCE = new DefaultCallAdapterFactory();

  //構(gòu)造方法
  @Override
  public CallAdapter<?> 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;
      }

      //將傳入的Call對象轉(zhuǎn)換為最后處理所需要的對象返回,在DefaultCallAdapterFactory中為將傳入其中的對象直接返回
      @Override public <R> Call<R> adapt(Call<R> call) {
        return call;
      }
    };
  }
}

這個是Retrofit中最為基本的CallAdapter,也只有在平臺為Java8或者無法判斷平臺時才會使用,也由于這個類的邏輯非常簡單,也可以通過這個類了解到CallAdapter.Factory最核心的兩個方法的作用

ExecutorCallAdapterFactory

ExecutorCallAdapterFactory類為Android平臺的默認(rèn)CallAdapter:

final class ExecutorCallAdapterFactory extends CallAdapter.Factory { 
  final Executor callbackExecutor;
  
  //構(gòu)造方法
  ExecutorCallAdapterFactory(Executor callbackExecutor) {
    this.callbackExecutor = callbackExecutor;
  }

  //獲取CallAdapter對象
  @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<?>>() {
      //獲取返回參數(shù)的類型
      @Override public Type responseType() {
        return responseType;
      }

      //將傳入的Call對象轉(zhuǎn)換為最后處理所需要的對象返回,在這里的返回類型為內(nèi)部類ExecutorCallbackCall
      @Override public <R> Call<R> adapt(Call<R> call) {
        return new ExecutorCallbackCall<>(callbackExecutor, call);
      }
    };
  }

  //這就是在ExecutorCallAdapterFactory中返回給外界去使用的對象,也就是在文章開頭調(diào)用了相應(yīng)的api方法后所返回的對象
  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;
    }

    //在文章開頭的使用示例中所傳入的CallBack實(shí)際就是在這里調(diào)用相應(yīng)的回調(diào)方法
    @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來源于針對當(dāng)前平臺的對象Platform中的defaultCallbackExecutor方法
          //在Android平臺中,該方法的返回語句為 return new MainThreadExecutor(); 
          //MainThreadExecutor的實(shí)現(xiàn)為通過handler將Runnable對象發(fā)送至主線程執(zhí)行
          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作用同上
          callbackExecutor.execute(new Runnable() {
            @Override public void run() {
              callback.onFailure(ExecutorCallbackCall.this, t);
            }
          });
        }
      });
    }
    
    //do something
  }

結(jié)語

那么,到現(xiàn)在為止,我們簡單梳理了Retrofit中的Call的創(chuàng)建流程與ServiceMethod類中的主要邏輯,而這些,也只是Retrofi中的一部分而已,而我也是第一次寫這樣的文章,加上我的技術(shù)還不到位,所以肯定會有很多的不足,歡迎大家來批評指正。

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

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

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