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
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.
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).
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.
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();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With