Created
December 23, 2017 21:51
-
-
Save bapspatil/bdf225ef2d2f0e51a63dadb657a3c64d to your computer and use it in GitHub Desktop.
Make Retrofit work offline with caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
not Working
Worked for me. Thank you
Working. Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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