Skip to content

Instantly share code, notes, and snippets.

@Tetr4
Last active February 1, 2020 05:17
Show Gist options
  • Save Tetr4/d10c5df0ad9218f967e0 to your computer and use it in GitHub Desktop.
Save Tetr4/d10c5df0ad9218f967e0 to your computer and use it in GitHub Desktop.
How to force a cached or network response on Android with Retrofit + OkHttp
OkHttpClient okHttpClient = new OkHttpClient();
try {
int cacheSize = 10 * 1024 * 1024 // 10 MiB
Cache cache = new Cache(getCacheDir(), cacheSize);
okHttpClient.setCache(cache);
} catch (IOException e) {
Log.e(TAG, "Could not set cache", e);
}
// Forces cache. Used for cache connection
RequestInterceptor cacheInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Cache-Control", "only-if-cached, max-stale=" + Integer.MAX_VALUE);
}
};
// Skips cache and forces full refresh. Used for service connection
RequestInterceptor noCacheInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Cache-Control", "no-cache");
}
};
// Build service connections
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint("http://yourserviceurl.com")
.setClient(new OkClient(okHttpClient))
// process request in the order they are called (e.g. cache first then service)
.setExecutors(Executors.newSingleThreadExecutor(), new MainThreadExecutor());
.setRequestInterceptor(noCacheInterceptor)
ServiceConnection serviceConnection = builder.build().create(ServiceConnection.class);
builder.setRequestInterceptor(cacheInterceptor);
ServiceConnection cacheConnection = builder.build().create(ServiceConnection.class);
/*
Now you can use the cacheConnection to show the user cached results immediately and
then try to receive network results using the serviceConnection.
*/
@mohitagrawal
Copy link

How do you use ServiceConnection?

@peter1408
Copy link

can you state the retrofit version and okhttp version you are using in the grade . Mine not resolving RequestInterceptor class.
Can you please also post a way you are requesting the Connections! I meant the complete source.

@Shrikant-B
Copy link

How to read cached response?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment