简体   繁体   English

可以在脱机时使用OKHttp进行改造以使用缓存数据

[英]Can Retrofit with OKHttp use cache data when offline

I'm trying to use Retrofit & OKHttp to cache HTTP responses. 我正在尝试使用Retrofit和OKHttp来缓存HTTP响应。 I followed this gist and, ended up with this code: 我遵循了要点,并最终获得了以下代码:

File httpCacheDirectory = new File(context.getCacheDir(), "responses");

HttpResponseCache httpResponseCache = null;
try {
     httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
     Log.e("Retrofit", "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);

api = new RestAdapter.Builder()
          .setEndpoint(API_URL)
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setClient(new OkClient(okHttpClient))
          .build()
          .create(MyApi.class);

And this is MyApi with the Cache-Control headers 这是MyApi,带有Cache-Control标头

public interface MyApi {
   @Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200")
   @GET("/api/v1/person/1/")
   void requestPerson(
           Callback<Person> callback
   );

First I request online and check the cache files. 首先,我在线请求并检查缓存文件。 The correct JSON response and headers are there. 正确的JSON响应和标头在那里。 But when I try to request offline, I always get RetrofitError UnknownHostException . 但是,当我尝试离线请求时,总是会得到RetrofitError UnknownHostException Is there anything else I should do to make Retrofit read the response from cache? 我还应该做些其他事情来使Retrofit从缓存中读取响应吗?

EDIT: Since OKHttp 2.0.x HttpResponseCache is Cache , setResponseCache is setCache 编辑:由于OKHttp 2.0.x HttpResponseCacheCachesetResponseCachesetCache

Edit for Retrofit 2.x: 编辑改造2.x:

OkHttp Interceptor is the right way to access cache when offline: OkHttp Interceptor是脱机时访问缓存的正确方法:

1) Create Interceptor: 1)创建拦截器:

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

2) Setup client: 2)安装客户端:

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

3) Add client to retrofit 3)将客户添加到改造中

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

Also check @kosiara - Bartosz Kosarzycki 's answer . 另请检查@kosiara-Bartosz Kosarzycki答案 You may need to remove some header from the response. 您可能需要从响应中删除一些标头。


OKHttp 2.0.x (Check the original answer): OKHttp 2.0.x(检查原始答案):

Since OKHttp 2.0.x HttpResponseCache is Cache , setResponseCache is setCache . 由于OKHttp 2.0.x HttpResponseCacheCache ,因此setResponseCachesetCache So you should setCache like this: 因此,您应该像这样设置setCache

        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);
        }
        String hostURL = context.getString(R.string.host_url);

        api = new RestAdapter.Builder()
                .setEndpoint(hostURL)
                .setClient(new OkClient(okHttpClient))
                .setRequestInterceptor(/*rest of the answer here */)
                .build()
                .create(MyApi.class);

Original Answer: 原始答案:

It turns out that server response must have Cache-Control: public to make OkClient to read from cache. 事实证明,服务器响应必须具有Cache-Control: public才能使OkClient从缓存读取。

Also If you want to request from network when available, you should add Cache-Control: max-age=0 request header. 另外,如果希望在可用时从网络请求,则应添加Cache-Control: max-age=0请求标头。 This answer shows how to do it parameterized. 此答案显示了如何对其进行参数化。 This is how I used it: 这是我的用法:

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

All of the anwsers above did not work for me. 上面所有的答案都不适合我。 I tried to implement offline cache in retrofit 2.0.0-beta2 . 我尝试在改造2.0.0-beta2中实现脱机缓存。 I added an interceptor using okHttpClient.networkInterceptors() method but received java.net.UnknownHostException when I tried to use the cache offline. 我使用okHttpClient.networkInterceptors()方法添加了一个拦截器,但是当我尝试脱机使用缓存时收到了java.net.UnknownHostException It turned out that I had to add okHttpClient.interceptors() as well. 原来,我还必须添加okHttpClient.interceptors()

The problem was that cache wasn't written to flash storage because the server returned Pragma:no-cache which prevents OkHttp from storing the response. 问题在于缓存未写入闪存,因为服务器返回了Pragma:no-cache ,这阻止了OkHttp存储响应。 Offline cache didn't work even after modifying request header values. 即使修改了请求标头值,脱机缓存也无法正常工作。 After some trial-and-error I got the cache to work without modifying the backend side by removing pragma from reponse instead of the request - response.newBuilder().removeHeader("Pragma"); 经过一番尝试后,我通过不从请求而不是从请求中除去编译指示来使缓存工作而不修改后端侧response.newBuilder().removeHeader("Pragma");

Retrofit: 2.0.0-beta2 ; 改造: 2.0.0-beta2 ; OkHttp: 2.5.0 OkHttp: 2.5.0

OkHttpClient okHttpClient = createCachedClient(context);
Retrofit retrofit = new Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(API_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
service = retrofit.create(RestDataResource.class);

... ...

private OkHttpClient createCachedClient(final Context context) {
    File httpCacheDirectory = new File(context.getCacheDir(), "cache_file");

    Cache cache = new Cache(httpCacheDirectory, 20 * 1024 * 1024);
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(cache);
    okHttpClient.interceptors().add(
            new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    String cacheHeaderValue = isOnline(context) 
                        ? "public, max-age=2419200" 
                        : "public, only-if-cached, max-stale=2419200" ;
                    Request request = originalRequest.newBuilder().build();
                    Response response = chain.proceed(request);
                    return response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheHeaderValue)
                        .build();
                }
            }
    );
    okHttpClient.networkInterceptors().add(
            new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request originalRequest = chain.request();
                    String cacheHeaderValue = isOnline(context) 
                        ? "public, max-age=2419200" 
                        : "public, only-if-cached, max-stale=2419200" ;
                    Request request = originalRequest.newBuilder().build();
                    Response response = chain.proceed(request);
                    return response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheHeaderValue)
                        .build();
                }
            }
    );
    return okHttpClient;
}

... ...

public interface RestDataResource {

    @GET("rest-data") 
    Call<List<RestItem>> getRestData();

}

My solution: 我的解决方案:

private BackendService() {

    httpCacheDirectory = new File(context.getCacheDir(),  "responses");
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(httpCacheDirectory, cacheSize);

    httpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
            .addInterceptor(OFFLINE_INTERCEPTOR)
            .cache(cache)
            .build();

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

    backendApi = retrofit.create(BackendApi.class);
}

private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = chain -> {
    Response originalResponse = chain.proceed(chain.request());
    String cacheControl = originalResponse.header("Cache-Control");

    if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
            cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, max-age=" + 10)
                .build();
    } else {
        return originalResponse;
    }
};

private static final Interceptor OFFLINE_INTERCEPTOR = chain -> {
    Request request = chain.request();

    if (!isOnline()) {
        Log.d(TAG, "rewriting request");

        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
        request = request.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                .build();
    }

    return chain.proceed(request);
};

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) MyApplication.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

building on @kosiara-bartosz-kasarzycki's answer , I created a sample project that properly loads from memory->disk->network using retrofit, okhttp, rxjava and guava. 在@ kosiara-bartosz-kasarzycki的答案的基础上 ,我创建了一个示例项目,该项目使用翻新,okhttp,rxjava和guava从内存->磁盘->网络正确加载。 https://github.com/digitalbuddha/StoreDemo https://github.com/digitalbuddha/StoreDemo

The answer is YES, based on the above answers, I started writing unit tests to verify all possible use cases : 答案是肯定的,基于上述答案,我开始编写单元测试以验证所有可能的用例:

  • Use cache when offline 离线使用缓存
  • Use cached response first until expired, then network 首先使用缓存的响应,直到过期,然后使用网络
  • Use network first then cache for some requests 首先使用网络,然后缓存一些请求
  • Do not store in cache for some responses 不要在缓存中存储某些响应

I built a small helper lib to configure OKHttp cache easily, you can see the related unittest here on Github : https://github.com/ncornette/OkCacheControl/blob/master/okcache-control/src/test/java/com/ncornette/cache/OkCacheControlTest.java 我构建了一个小的帮助程序库来轻松配置OKHttp缓存,您可以在Github上查看相关的单元测试: https : //github.com/ncornette/OkCacheControl/blob/master/okcache-control/src/test/java/com/ ncornette / cache / OkCacheControlTest.java

Unittest that demonstrates the use of cache when offline : 演示脱机时如何使用缓存的单元测试:

@Test
public void test_USE_CACHE_WHEN_OFFLINE() throws Exception {
    //given
    givenResponseInCache("Expired Response in cache", -5, MINUTES);
    given(networkMonitor.isOnline()).willReturn(false);

    //when
    //This response is only used to not block when test fails
    mockWebServer.enqueue(new MockResponse().setResponseCode(404));
    Response response = getResponse();

    //then
    then(response.body().string()).isEqualTo("Expired Response in cache");
    then(cache.hitCount()).isEqualTo(1);
}

As you can see, cache can be used even if it has expired. 如您所见,即使缓存已过期也可以使用。 Hope it will help. 希望它会有所帮助。

Cache with Retrofit2 and OkHTTP3: 使用Retrofit2和OkHTTP3进行缓存:

OkHttpClient client = new OkHttpClient
  .Builder()
  .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
  .addInterceptor(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      if (NetworkUtils.isNetworkAvailable()) {
        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
      } else {
        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
      }
      return chain.proceed(request);
    }
  })
  .build();

NetworkUtils.isNetworkAvailable() static method: NetworkUtils.isNetworkAvailable()静态方法:

public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
    }

Then just add client to the retrofit builder: 然后只需将客户端添加到改造生成器中:

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

Original source: https://newfivefour.com/android-retrofit2-okhttp3-cache-network-request-offline.html 原始来源: https : //newfivefour.com/android-retrofit2-okhttp3-cache-network-request-offline.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM