Skip to content

Instantly share code, notes, and snippets.

@nhachicha
Last active November 10, 2015 11:00
Show Gist options
  • Save nhachicha/b10d2e177a1bd1b4be7b to your computer and use it in GitHub Desktop.
Save nhachicha/b10d2e177a1bd1b4be7b to your computer and use it in GitHub Desktop.
package com.nabilhachicha.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class CachedResponseActivity extends Activity {
private OkHttpClient mClient;
private final long TWO_WEEKS = TimeUnit.DAYS.toSeconds(14);
private final String TAG = CachedResponseActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Allow network call on main Thread (DON'T do this in production!)
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mClient = new OkHttpClient();
// Set up cache
File httpCacheDir = new File(getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB cache
Cache cache = new Cache(httpCacheDir, httpCacheSize);
mClient.setCache(cache);
// Add interceptor to automatically fallback to the cache in case of network error
mClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
boolean exceptionThrown = false;
Request request = chain.request();
Response response = null;
try {
response = chain.proceed(request);
} catch (IOException e) {//Ex: UnknownHostException
exceptionThrown = true;
}
// If the regular request fail, try our cache if available (stale cached responses better than nothing)
if (exceptionThrown || !response.isSuccessful()) {
Request cachedRequest = request.newBuilder() //Request are immutable so we clone the existing request
.removeHeader("Cache-Control")
.addHeader("Cache-Control", "max-stale=" + TWO_WEEKS).build();
response = chain.proceed(cachedRequest);
}
return response;
}
});
request();
}
// Queries
private void request() {
try {
String url = "https://api.github.com/users/octocat/repos";
Request request = new Request.Builder()
.url(url)
.addHeader("Cache-Control", "max-age=" + TWO_WEEKS)
.build();
Response response = mClient.newCall(request).execute();
String result = response.body().string();
Log.i(TAG, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@nhachicha
Copy link
Author

Use Http Cache-Control strategy to fallback to cache response when going offline (ex: Flight mode will throw UnknownHostException)

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