Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Cache of okhttp

i know to disable cache of okhttp is to call Request.cacheControl(CacheControl.FORCE_NETWORK). Is it possible to set the cacheControl from OkHttpClient.class? Because i have 1 client for all my request. So i want to disable cache for all the request by disabling it from the okhttpClient

like image 922
zihadrizkyef Avatar asked Mar 15 '17 01:03

zihadrizkyef


People also ask

Can I delete OkHttp cache?

Deleting the cache when it is no longer needed can be done. However this may delete the purpose of the cache which is designed to persist between app restarts.

What is OkHttp cache?

OkHttp is an HTTP client that's efficient by default: 1. HTTP/2 support allows all requests to the same host to share a socket. 2. Connection pooling reduces request latency (if HTTP/2 isn't available).

What is OkHttp cache in android?

Basically: The client will send out something like timestamp or Etag of the last request. The server can then check if there is some data has changed in during that period of time or not. If nothing has changed, the server can just give a special code (304 -not modified) without sending the whole same response again.


2 Answers

add interceptor to your client, and add cache control header in interceptor.check sample code below:

    Interceptor interceptor = new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder().addHeader("Cache-Control", "no-cache");
            request = builder.build();
            return chain.proceed(request);
        }
    };

    OkHttpClient mClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();
like image 171
YT Wang Avatar answered Oct 16 '22 14:10

YT Wang


Use this to build Retrofit and provide cache as null the API will not cache anything.

private OkHttpClient createOkHttpClient() {
    return new OkHttpClient.Builder()
            ...
            .cache(null)
            .build();
}
like image 28
VikasGoyal Avatar answered Oct 16 '22 15:10

VikasGoyal