4

I am trying to cache the http response through OKhttp but unable to find some good example or documentation.

Thanks for any help

Ashish Rajvanshi
  • 466
  • 4
  • 15

3 Answers3

9

this will cache all your response for 2 minutes

OkHttpClient provideOkHttpClient () {
    Cache cache = new Cache(new File(context.getCacheDir(), "http-cache"), 10 * 1024 * 1024);
    return new OkHttpClient.Builder()
            .addNetworkInterceptor(provideCacheInterceptor())
            .cache(cache)
            .build();
}

Interceptor provideCacheInterceptor () {
    return new Interceptor() {
        @Override
        public Response intercept (Chain chain) throws IOException {
            Response response = chain.proceed( chain.request() );
            CacheControl cacheControl = new CacheControl.Builder()
                    .maxAge( 2, TimeUnit.MINUTES )
                    .build();

            return response.newBuilder()
                    .header("Cache-Control", cacheControl.toString() )
                    .build();
        }
    };
}
orium
  • 3,743
  • 2
  • 24
  • 27
7
public final class FeedInterceptor {

private final static String TAG = FeedInterceptor.class.getSimpleName();

/**
 * Validate cache, return stream. Return cache if no network.
 * @param context
 * @return
 */
public static Interceptor getOnlineInterceptor(final Context context){
    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            String headers = response.header("Cache-Control");
            if(NetworkUtils.isConnected(context) && (headers == null
                  || headers.contains("no-store")
                  || headers.contains("must-revalidate")
                  || headers.contains("no-cache")
                  || headers.contains("max-age=0"))) {

                LOGD(TAG, "Returning fresh response");
                return response.newBuilder()
                        .header("Cache-Control", "public, max-age=600")
                        .build();
            } else{
                LOGD(TAG, "Returning old response");
                return response;
            }
        }
    };

    return interceptor;
}

/**
 * Get me cache.
 * @param context
 * @return
 */
public static Interceptor getOfflineInterceptor(final Context context){
    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if(!NetworkUtils.isConnected(context)){
                request = request.newBuilder()
                        .header("Cache-Control", "public, only-if-cached")
                        .build();
            }

            return chain.proceed(request);
        }
    };

    return interceptor;
}

} // End FeedInterceptor

And the client:

private OkHttpClient createCacheClient(Context context){

    File httpCacheDirecotory = new File(context.getCacheDir(), FILE);
    Cache cache = new Cache(httpCacheDirecotory, CACHE_SIZE);

    return new OkHttpClient.Builder()
            .addNetworkInterceptor(FeedInterceptor.getOnlineInterceptor(context))
            .addInterceptor(FeedInterceptor.getOfflineInterceptor(context))
            .cache(cache)
            .build();
}

Reference

David Newcomb
  • 10,639
  • 3
  • 49
  • 62
parohy
  • 2,070
  • 2
  • 22
  • 38
2

There is a sample here CacheResponse.java

Cache cache = new Cache(cacheDirectory, cacheSize);

client = new OkHttpClient.Builder()
    .cache(cache)
    .build();

The javadoc for Cache has examples for forcing fresh or cached responses.

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
  • Yuri it is working, but i want to do runtime memory cache instead of disk memory and also wants to know how can i remove cache further. I am using the common http Client here. – Ashish Rajvanshi Jul 12 '16 at 12:30
  • The design of Cache is based around a real filesystem AFAIK. It doesn't look possible by public API. I suspect you need to either use Cache with a FileSystem or implement your own caching strategy in interceptors – Yuri Schimke Jul 13 '16 at 00:30