Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 616
Ashish Rajvanshi Avatar asked Dec 02 '22 12:12

Ashish Rajvanshi


1 Answers

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();
        }
    };
}
like image 159
orium Avatar answered Dec 05 '22 08:12

orium