Ashish Rajvanshi
Ashish Rajvanshi

Reputation: 466

How to Cache the response in squareup.okhttp3

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

Thanks for any help

Upvotes: 4

Views: 5946

Answers (3)

parohy
parohy

Reputation: 2180

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

Upvotes: 7

Yuri Schimke
Yuri Schimke

Reputation: 13458

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.

Upvotes: 2

orium
orium

Reputation: 3813

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

Upvotes: 9

Related Questions