Retrofit - Okhttp client How to cache the response

拈花ヽ惹草 提交于 2019-11-27 17:32:31
ImMathan

As per Retrofit 1.9.0 which uses OkClient does not have Caching support. We have to use OkHttpClient instance by Square OkHttpClient library.

You can compile by compile 'com.squareup.okhttp:okhttp:2.3.0'

Before everything retrofit caches by response headers like

Cache-Control:max-age=120,only-if-cached,max-stale

** 120 is seconds.

You can read more about headers here.

Caching headers are mostly instructed by server response. Try to implement cache headers in servers. If you don't have an option, yes retrofit has it.

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .header("Cache-Control", String.format("max-age=%d, only-if-cached, max-stale=%d", 120, 0))
                .build();
    }
};

Where to cache:

private static void createCacheForOkHTTP() {
    Cache cache = null;
    cache = new Cache(getDirectory(), 1024 * 1024 * 10);
    okHttpClient.setCache(cache);
}

// returns the file to store cached details
private File getDirectory() {
    return new File(“location”);
}

Add interceptor to the OkHttpClient instance:

okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);

And finally add OkHttpClient to the RestAdapter:

RestAdapter.setClient(new OkClient(okHttpClient));

And you can go through this slide for more reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!