欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android開發(fā)Retrofit源碼分析

 更新時(shí)間:2022年07月27日 17:17:13   作者:jiangpan  
這篇文章主要為大家介紹了Android開發(fā)Retrofit源碼分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

項(xiàng)目結(jié)構(gòu)

把源碼 clone 下來(lái) , 可以看到 retrofit 整體結(jié)構(gòu)如下

圖 http包目錄下就是一些http協(xié)議常用接口 , 比如 請(qǐng)求方法 url , 請(qǐng)求體, 請(qǐng)求行 之類的

retrofit 使用

把retrofit使用作為分析的切入口吧 , retrofit單元測(cè)試使用如下

public final class BasicCallTest {
    @Rule public final MockWebServer server = new MockWebServer();
    interface Service {
        @GET("/") Call<ResponseBody> getBody();
    }
    @Test public void responseBody() throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .build();
        Service example = retrofit.create(Service.class);
        server.enqueue(new MockResponse().setBody("1234"));
        Response<ResponseBody> response = example.getBody().execute();
        assertEquals("1234", response.body().string());
    }
}

Retrofit 構(gòu)建 , 以構(gòu)建者模式構(gòu)建出Retrofit

可以看到builer可以配置baseUrl , 回調(diào)線程池 , 還有一些適配器的工廠 , 這些適配器的作用后面說(shuō)

Retrofit #create

從create 方法開始分析 , 跟進(jìn)看下create 方法

public <T> T create(final Class<T> service) {
    validateServiceInterface(service);
    return (T)
        Proxy.newProxyInstance(
        service.getClassLoader(),
        new Class<?>[] {service},
        new InvocationHandler() {
            private final Object[] emptyArgs = new Object[0];
            @Override
            public @Nullable 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);
                }
                args = args != null ? args : emptyArgs;
                Platform platform = Platform.get();
                return platform.isDefaultMethod(method)
                    ? platform.invokeDefaultMethod(method, service, proxy, args)
                    : loadServiceMethod(method).invoke(args);
            }
        });
}

service 是請(qǐng)求的接口的class , 動(dòng)態(tài)代理只能是接口 , 所以validateServiceInterface 先驗(yàn)證是不是接口 , 不是接口則拋異常。

method.getDeclaringClass() 獲取聲明類的Class。

比如 A類 有個(gè)method , method.getDeclaringClass() 返回為A.class , 如果method聲明類是Object.class 則直接method.invoke , 往下執(zhí)行毫無(wú)意義。

Platform#get()會(huì)根據(jù)當(dāng)前平臺(tái)獲取Platform 。

有點(diǎn)類似狀態(tài)模式思想 , 根據(jù)當(dāng)前的平臺(tái)選擇合適的子類

public boolean isDefaultMethod(Method method) {
    return method.isDefault();
    }

isDefault , 在接口類型中以default關(guān)鍵字聲明 則返回true, 比如

interface InterfaceWithDefault {
    void firstMethod();
    default void newMethod() {
        System.out.println("newMethod");
    }
}

所以此處會(huì)返回 false 接著調(diào)用 loadServiceMethod。

ServiceMethod #parseAnnotations

跟進(jìn)ServiceMethod #parseAnnotations

  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
    RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

根據(jù)當(dāng)前的方法信息構(gòu)建出RequestFactory , 然后把具體實(shí)現(xiàn)細(xì)節(jié)交給HttpServiceMethod 處理 , HttpServiceMethod 繼承自ServiceMethod , 有三個(gè)子類 。

我們?cè)贏pi.class定義的方法 , 解析并不是由HttpServiceMethod 完成 , 而是由RequestFactory去處理的 , 比如解析方法的注解。

更多的解析方法如下

方法解析的細(xì)節(jié)就不說(shuō)了 , 繼續(xù)看RequestFactory 這個(gè)類 , 這個(gè)類的作用難道就是負(fù)責(zé)方法信息的解析 , 感覺(jué)和名字不太符合 , RequestFactory 顧名思義應(yīng)該是用來(lái)構(gòu)建Request的工廠 , 果不其然內(nèi)部還有個(gè) create 方法 , 用來(lái)構(gòu)建okhttp3.Request的

  //RequestFactory #create
okhttp3.Request create(Object[] args) throws IOException {
    return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build();
  }

就只有這一個(gè)create方法 , 難道retrofit 就只能使用okhttp來(lái)負(fù)責(zé)網(wǎng)絡(luò)請(qǐng)求 ? 答案是肯定的 , 從最開始的 loadServiceMethod(method).invoke(args)也可以看出 , 方法里面只構(gòu)建出OkHttpCall 沒(méi)提供api可以讓我們切換到其他的網(wǎng)絡(luò)請(qǐng)求庫(kù)。

但是 , Call 又抽象成接口的形式 ,如下, 這么做的目的可能是以后便于框架的維護(hù)

沿途風(fēng)景再美麗 , 也要回到主線路 , 繼續(xù)分析 HttpServiceMethod#parseAnnotations

HttpServiceMethod#parseAnnotations

這個(gè)方法太長(zhǎng) , 貼關(guān)鍵代碼吧

 static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
      Retrofit retrofit, Method method, RequestFactory requestFactory) {
    boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
    boolean continuationWantsResponse = false;
    boolean continuationBodyNullable = false;
    boolean continuationIsUnit = false;
    Annotation[] annotations = method.getAnnotations();
    Type adapterType;
    if (isKotlinSuspendFunction) {
      Type[] parameterTypes = method.getGenericParameterTypes();
      Type responseType =
          Utils.getParameterLowerBound(
              0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
      if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
        continuationWantsResponse = true;
      }
    } else {
      //非kt 協(xié)程情況
      adapterType = method.getGenericReturnType();
    }
    CallAdapter<ResponseT, ReturnT> callAdapter =
        createCallAdapter(retrofit, method, adapterType, annotations);
    Type responseType = callAdapter.responseType();
    Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);
    okhttp3.Call.Factory callFactory = retrofit.callFactory;
    if (!isKotlinSuspendFunction) {
        //非kt 協(xié)程情況
      return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
    } else if (continuationWantsResponse) {
      return (HttpServiceMethod<ResponseT, ReturnT>)
          new SuspendForResponse<>(
              requestFactory,
              callFactory,
              responseConverter,
              (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
    } else {
      return (HttpServiceMethod<ResponseT, ReturnT>)
          new SuspendForBody<>(
              requestFactory,
              callFactory,
              responseConverter,
              (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
              continuationBodyNullable,
              continuationIsUnit);
    }
  }

構(gòu)建出HttpServiceMethod分兩種情況 :

  • kotlin 協(xié)程情況
  • 非Kotlin 協(xié)程情況

第二種 非Kotlin協(xié)程情況

第一種情況稍許復(fù)雜 , 先分析第二種

adapterType = method.getGenericReturnType();

 @GET("/") Call<ResponseBody> getBody();

如果是上面代碼 , method.getGenericReturnType() = Call , 然后根據(jù)方法的返回值類型 / 方法注解信息 , 構(gòu)建出CallAdapter 。

createCallAdapter() 方法會(huì)使用 CallAdapter.Factory 構(gòu)建CallAdapter , 因?yàn)槌跏蓟痳etrofit的時(shí)候沒(méi)有配置CallAdapter.Factory , 所以會(huì)使用默認(rèn)的DefaultCallAdapterFactory。

最終會(huì)進(jìn)入DefaultCallAdapterFactory#get 。

DefaultCallAdapterFactory#get

這個(gè)方法作用就是返回CallAdapter , 修改下源碼加入兩個(gè)打印。

  public @Nullable CallAdapter<?, ?> get(
      Type returnType, Annotation[] annotations, Retrofit retrofit) {
    final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
    System.out.println("TAG" + " ->" + "returnType = " +getRawType(returnType) .getSimpleName());
    System.out.println("TAG" + " ->" + "responseType = " +getRawType(responseType) .getSimpleName());
    return new CallAdapter<Object, Call<?>>() {
      @Override
      public Type responseType() {
        return responseType;
      }
      @Override
      public Call<Object> adapt(Call<Object> call) {
        return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
      }
    };
  }

運(yùn)行可以看到以下打印信息

returnType = Call ,responseType =ResponseBody 。

總結(jié)一下 , returnType就是方法返回值 , responseType 就是方法返回值上的泛型 DefaultCallAdapterFactory會(huì)根據(jù)平臺(tái)環(huán)境去構(gòu)建。

以Android24分析 , DefaultCallAdapterFactory(Executor callbackExecutor) , 構(gòu)造方法中 , 線程池為主線程池 , 在retrofit初始化的時(shí)候添加到 到callAdapterFactories 集合中。

至此 , CallAdapterFactory 和 CallAdapter 分析完了 , 總結(jié)下就是給Call (retrofit內(nèi)存只有OkHttpCall 作為唯一實(shí)現(xiàn)類)做適配 , 讓其可以在 Rxjava / 協(xié)程 等各個(gè)環(huán)境中使用 Call。

非kt 協(xié)程情況下 , parseAnnotations 方法最終返回的是將requestFactory , callFactory , responseConverter, callAdapter 封裝好的CallAdapted 對(duì)象。

再次回到夢(mèng)開始的地方Retrofit#create 方法 , loadServiceMethod獲取的ServiceMethod最終實(shí)現(xiàn)類為CallAdapted , 獲取之后會(huì)調(diào)用invoke方法 , invoke是一個(gè)final方法 , 里面構(gòu)建了OkHttpCall , 然后調(diào)用了adapt方法 , adapt中調(diào)用了callAdapter.adapt(call)。

   @Override
    protected ReturnT adapt(Call&lt;ResponseT&gt; call, Object[] args) {
      return callAdapter.adapt(call);
    }

這里的ReturnT 就是ExecutorCallbackCall<>(executor, call) 對(duì)象 , 所以 example.getBody().execute() 就是調(diào)用ExecutorCallbackCall#execute方法

 //ExecutorCallbackCall#execute
 public Response<T> execute() throws IOException {
      return delegate.execute();
    }

delegate為OkHttpCall , 所以就調(diào)用到OkHttpCallCall#execute方法 , 這里就轉(zhuǎn)給Okhttp去請(qǐng)求網(wǎng)絡(luò)加載數(shù)據(jù)了 , 代碼就不貼了 , 我們看下網(wǎng)絡(luò)請(qǐng)求之后 , 數(shù)據(jù)Response 的處理 , 關(guān)鍵代碼OkHttpCall#parseResponse。

 Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();
    ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
    try {
      T body = responseConverter.convert(catchingBody);
      return Response.success(body, rawResponse);
    } 
  }

responseConverter 在 HttpServiceMethod#parseAnnotations 方法中獲取 , 回應(yīng)數(shù)據(jù)轉(zhuǎn)換器 , 把數(shù)據(jù)轉(zhuǎn)換成我們可以直接使用的對(duì)象 , 比如我們常用的 GsonConverterFactory。

最后把轉(zhuǎn)換好之后的數(shù)據(jù) , 封裝成Response對(duì)象返回。

response.body()就是responseConverter 轉(zhuǎn)換后的數(shù)據(jù) 來(lái)張大致流程圖感受下吧

第一種 Kotlin協(xié)程情況

其實(shí)大致流程第二種情況分析的差不多了 , 接下來(lái)分析下Retrofit對(duì)于kotlin的特殊處理吧。

 if (Utils.getRawType(parameterType) == Continuation.class) {
              isKotlinSuspendFunction = true;
              return null;
            }

協(xié)程掛起方法 , 第一個(gè)參數(shù)為Continuation , 所以判斷是不是掛起方法也很簡(jiǎn)單 , 根據(jù)ResponseType 去構(gòu)建協(xié)程專用的HttpServiceMethod , 主要有兩類。

  • SuspendForResponse , 對(duì)應(yīng)type為Continuation<Response>
  • SuspendForBody , 對(duì)應(yīng)type為Continuation

這里看下 SuspendForBody 實(shí)現(xiàn) , 套娃情況就不分析了。

如果是這樣使用 , 最終會(huì)調(diào)到SuspendForBody #adapt。

 @Override
    protected Object adapt(Call<ResponseT> call, Object[] args) {
      call = callAdapter.adapt(call);
      Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1];
      try {
         //去掉干擾代碼 , 僅保留這個(gè)
          return KotlinExtensions.awaitNullable(call, continuation);
      }
    }

這個(gè)地方就很關(guān)鍵了 , java 直接調(diào)kotlin 協(xié)程 suspend 方法。

KotlinExtensions.awaitNullable 會(huì)調(diào)到KotlinExtensions#await方法。

retrofit與協(xié)程適配的細(xì)節(jié)都在 KotlinExtensions這個(gè)類里。

進(jìn)入await , 可以看到使用suspendCancellableCoroutine把回調(diào)裝換成協(xié)程。

@JvmName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
    return suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation {
            cancel()
        }
        enqueue(object : Callback<T?> {
            override fun onResponse(call: Call<T?>, response: Response<T?>) {
                if (response.isSuccessful) {
                    continuation.resume(response.body())
                } else {
                    continuation.resumeWithException(HttpException(response))
                }
            }
            override fun onFailure(call: Call<T?>, t: Throwable) {
                continuation.resumeWithException(t)
            }
        })
    }
}

其實(shí)內(nèi)部也是調(diào)用 OkHttp Call.enqueue() , 只不過(guò)是用suspendCancellableCoroutine給協(xié)程做了一層包裝處理

通過(guò) suspendCancellableCoroutine包裝之后使用就很簡(jiǎn)單了。

 GlobalScope.launch {
            try {
                val result = xxxApi.getXxx()
            } catch (exception: Exception) {
            }
        }

總結(jié)

Call 這個(gè)接口用于與網(wǎng)絡(luò)請(qǐng)求庫(kù)做適配 , 比如Okhttp。

CallAdapter 用于retrofit 與各種環(huán)境搭配使用做適配 , 比如rxjava / 協(xié)程 / java。

Converter 用于將請(qǐng)求結(jié)果轉(zhuǎn)換實(shí)體類Bean 或者其他。

用到的設(shè)計(jì)模式有: 動(dòng)態(tài)代理/靜態(tài)代理 / 構(gòu)建者 / 工廠 / 適配器 / 狀態(tài) 等。

以上就是Android開發(fā)Retrofit源碼分析的詳細(xì)內(nèi)容,更多關(guān)于Android Retrofit源碼分析的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論