首頁  >  文章  >  Java  >  OKHttp改造可以在離線時利用快取資料嗎?

OKHttp改造可以在離線時利用快取資料嗎?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-05 06:38:02701瀏覽

Can Retrofit with OKHttp Utilize Cached Data When Offline?

Retrofit 與 OKHttp 可以在離線時利用快取資料嗎?

在嘗試使用 Retrofit 和 OKHttp 快取 HTTP 回應時,您遇到了以下問題離線時取得 RetrofitError UnknownHostException。這表明 Retrofit 無法檢索快取的資料。要解決此問題,需要進行以下修改:

針對Retrofit 2.x 進行編輯:

  • 實作OkHttp 攔截器來管理快取邏輯:

    <code class="java">private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {
          Response originalResponse = chain.proceed(chain.request());
          if (Utils.isNetworkAvailable(context)) {
              int maxAge = 60; // read from cache for 1 minute
              return originalResponse.newBuilder()
                      .header("Cache-Control", "public, max-age=" + maxAge)
                      .build();
          } else {
              int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
              return originalResponse.newBuilder()
                      .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                      .build();
          }
      }
    }</code>
  • 為OkHttpClient 設定攔截器與快取:

    <code class="java">OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
    
    //setup cache
    File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(httpCacheDirectory, cacheSize);
    
    //add cache to the client
    client.setCache(cache);</code>
  • 將OkHttpClient >

    <code class="java">Retrofit retrofit = new Retrofit.Builder()
          .baseUrl(BASE_URL)
          .client(client)
          .addConverterFactory(GsonConverterFactory.create())
          .build();</code>
OKHttp 2.0.x:

    調整您的客戶端設定以反映更新的語法:
  • <code class="java">      File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    
          Cache cache = null;
          try {
              cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
          } catch (IOException e) {
              Log.e("OKHttp", "Could not create http cache", e);
          }
    
          OkHttpClient okHttpClient = new OkHttpClient();
          if (cache != null) {
              okHttpClient.setCache(cache);
          }
          ...</code>

原始答案:

    確保伺服器回應包含Cache-Control: public 以啟用Retrofit 從快取中讀取。
  • 實作一個請求攔截器,根據網路可用性設定Cache-Control 標頭:

    <code class="java">RestAdapter.Builder builder= new RestAdapter.Builder()
     .setRequestInterceptor(new RequestInterceptor() {
          @Override
          public void intercept(RequestFacade request) {
              request.addHeader("Accept", "application/json;versions=1");
              if (MyApplicationUtils.isNetworkAvailable(context)) {
                  int maxAge = 60; // read from cache for 1 minute
                  request.addHeader("Cache-Control", "public, max-age=" + maxAge);
              } else {
                  int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                  request.addHeader("Cache-Control", 
                      "public, only-if-cached, max-stale=" + maxStale);
              }
          }
    });</code>
透過實作這些修改,Retrofit 將在離線時正確利用快取數據,如下所示只要伺服器回應包含適當的快取控制標頭。

以上是OKHttp改造可以在離線時利用快取資料嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn