最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

項目結(jié)構(gòu)

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

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

retrofit 使用

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

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)線程池 , 還有一些適配器的工廠 , 這些適配器的作用后面說

Retrofit #create

從create 方法開始分析 , 跟進看下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 是請求的接口的class , 動態(tài)代理只能是接口 , 所以validateServiceInterface 先驗證是不是接口 , 不是接口則拋異常。

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

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

Platform#get()會根據(jù)當前平臺獲取Platform 。

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

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

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

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

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

ServiceMethod #parseAnnotations

跟進ServiceMethod #parseAnnotations

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

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

我們在Api.class定義的方法 , 解析并不是由HttpServiceMethod 完成 , 而是由RequestFactory去處理的 , 比如解析方法的注解。

更多的解析方法如下

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

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

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

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

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

HttpServiceMethod#parseAnnotations

這個方法太長 , 貼關鍵代碼吧

 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é)程情況

第一種情況稍許復雜 , 先分析第二種

adapterType = method.getGenericReturnType();

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

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

createCallAdapter() 方法會使用 CallAdapter.Factory 構(gòu)建CallAdapter , 因為初始化retrofit的時候沒有配置CallAdapter.Factory , 所以會使用默認的DefaultCallAdapterFactory。

最終會進入DefaultCallAdapterFactory#get 。

DefaultCallAdapterFactory#get

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

  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);
      }
    };
  }

運行可以看到以下打印信息

returnType = Call ,responseType =ResponseBody 。

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

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

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

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

再次回到夢開始的地方Retrofit#create 方法 , loadServiceMethod獲取的ServiceMethod最終實現(xiàn)類為CallAdapted , 獲取之后會調(diào)用invoke方法 , invoke是一個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) 對象 , 所以 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去請求網(wǎng)絡加載數(shù)據(jù)了 , 代碼就不貼了 , 我們看下網(wǎng)絡請求之后 , 數(shù)據(jù)Response 的處理 , 關鍵代碼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 方法中獲取 , 回應數(shù)據(jù)轉(zhuǎn)換器 , 把數(shù)據(jù)轉(zhuǎn)換成我們可以直接使用的對象 , 比如我們常用的 GsonConverterFactory。

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

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

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

其實大致流程第二種情況分析的差不多了 , 接下來分析下Retrofit對于kotlin的特殊處理吧。

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

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

  • SuspendForResponse , 對應type為Continuation<Response>
  • SuspendForBody , 對應type為Continuation

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

如果是這樣使用 , 最終會調(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 {
         //去掉干擾代碼 , 僅保留這個
          return KotlinExtensions.awaitNullable(call, continuation);
      }
    }

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

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

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

進入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)
            }
        })
    }
}

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

通過 suspendCancellableCoroutine包裝之后使用就很簡單了。

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

總結(jié)

Call 這個接口用于與網(wǎng)絡請求庫做適配 , 比如Okhttp。

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

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

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

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

相關文章

  • 在Android系統(tǒng)中使用gzip進行數(shù)據(jù)傳遞實例代碼

    在Android系統(tǒng)中使用gzip進行數(shù)據(jù)傳遞實例代碼

    HTTP協(xié)議上的GZIP編碼是一種用來改進WEB應用程序性能的技術,4.4MB的文本數(shù)據(jù)經(jīng)過Gzip傳輸?shù)娇蛻舳酥笞優(yōu)?92KB,壓縮效率極高,下面與大家分享下具體的實現(xiàn)
    2013-06-06
  • Android在Fragment中實現(xiàn)監(jiān)聽觸摸事件

    Android在Fragment中實現(xiàn)監(jiān)聽觸摸事件

    這篇文章主要給大家介紹了Android在Fragment中實現(xiàn)監(jiān)聽觸摸事件的相關資料,文中介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。
    2017-05-05
  • 詳解dex優(yōu)化對Arouter查找路徑的影響

    詳解dex優(yōu)化對Arouter查找路徑的影響

    dex簡單說就是優(yōu)化后的android版.exe。每個apk安裝包里都有。相對于PC上的java虛擬機能運行.class,android上的Davlik虛擬機能運行.dex。本文將著重介紹dex優(yōu)化對Arouter查找路徑的影響
    2021-06-06
  • Android多線程及異步處理問題詳細探討

    Android多線程及異步處理問題詳細探討

    究其為啥需要多線程的本質(zhì)就是異步處理,直觀一點說就是不要讓用戶感覺到“很卡”為了提高用戶體驗那是必須要使用的
    2013-06-06
  • 安卓GET與POST網(wǎng)絡請求的三種方式

    安卓GET與POST網(wǎng)絡請求的三種方式

    今天小編就為大家分享一篇關于安卓GET與POST網(wǎng)絡請求的三種方式,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Android 讀取sdcard上的圖片實例(必看)

    Android 讀取sdcard上的圖片實例(必看)

    下面小編就為大家?guī)硪黄狝ndroid 讀取sdcard上的圖片實例(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • Android利用animation-list實現(xiàn)幀動畫

    Android利用animation-list實現(xiàn)幀動畫

    這篇文章主要為大家詳細介紹了Android利用animation-list實現(xiàn)幀動畫,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Android 讀取Properties配置文件的小例子

    Android 讀取Properties配置文件的小例子

    這篇文章主要介紹了Android 讀取Properties配置文件的小例子,有需要的朋友可以參考一下
    2014-01-01
  • Android手機管理工具類詳解

    Android手機管理工具類詳解

    這篇文章主要為大家詳細介紹了Android手機管理工具類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • Android實現(xiàn)放大鏡效果的方法實例(附源碼)

    Android實現(xiàn)放大鏡效果的方法實例(附源碼)

    這篇文章主要給大家介紹了利用Android實現(xiàn)放大鏡效果的方法實例,文中給出了詳細的介紹和示例代碼,文章的結(jié)尾更是給出了源碼供大家下載學習,有需要的朋友們下面來一起看看吧。
    2017-01-01

最新評論

洪洞县| 洛南县| 高阳县| 北辰区| 天水市| 含山县| 南华县| 石门县| 航空| 甘谷县| 高密市| 柳河县| 南木林县| 吉林省| 泸溪县| 临泽县| 邹平县| 洮南市| 红桥区| 台南县| 建瓯市| 茶陵县| 凤凰县| 永年县| 泰宁县| 茂名市| 永嘉县| 东乡县| 宜宾县| 垣曲县| 民乐县| 永和县| 即墨市| 游戏| 湄潭县| 鹤山市| 淮阳县| 鱼台县| 武平县| 滁州市| 隆昌县|