Skip to content

Instantly share code, notes, and snippets.

@bapspatil
Created December 23, 2017 21:51
Show Gist options
  • Save bapspatil/bdf225ef2d2f0e51a63dadb657a3c64d to your computer and use it in GitHub Desktop.
Save bapspatil/bdf225ef2d2f0e51a63dadb657a3c64d to your computer and use it in GitHub Desktop.
Make Retrofit work offline with caching
package bapspatil.pantheon.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.IOException;
import bapspatil.pantheon.network.RetrofitAPI;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by bapspatil
*/
public class RetrofitCached {
public static Boolean hasNetwork(Context context) {
Boolean isConnected = false; // Initial Value
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting())
isConnected = true;
return isConnected;
}
public static Retrofit getCacheEnabledRetrofit(final Context context) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(context.getCacheDir(), 5 * 1024 * 1024))
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if(hasNetwork(context))
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
else
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
return chain.proceed(request);
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.baseUrl(RetrofitAPI.BASE_URL)
.build();
return retrofit;
}
}
@yankarinRG
Copy link

Helllo, does this cache the request or the response? I have the need that, if my app sends a POST request to add an object and there is no internet connection, then the request is cached and when the app returns online, the request is sent so that object is not lost. Thank you for your time

@hafeezsohaib
Copy link

not Working

@sallyjayz
Copy link

Worked for me. Thank you

@ybansal830
Copy link

Working. Thank you

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