Skip to content

Instantly share code, notes, and snippets.

@gtomek
Last active October 20, 2015 15:43
Show Gist options
  • Save gtomek/5d9fe06efdcdb8e4163f to your computer and use it in GitHub Desktop.
Save gtomek/5d9fe06efdcdb8e4163f to your computer and use it in GitHub Desktop.
Get saved OkHttp cache
/**
* Returns response cached by OkHttp.
*
* @param url URL used to make original request
*/
@Nullable
private List<PostModel> getCachedDataIfExist(final String url) {
// OkHttpClient saves cache using DiskLruCache, the cached data is stored in the cache dir in the files
// which names are created by md5 hash function, e.g. for
// http://www.yourserver.com/posts?filter[posts_per_page]=10&page=1
// the file name is 0fcd35e5c6a73ab6eb01295765ffd8e7.1
// we can use it to retrieve the previously cached data if the data exist
String urlKey = Util.md5Hex(url);
// read file
File cacheDir = new File(getActivity().getCacheDir(), getActivity().getString(R.string.http_cache_dir_name));
try {
// cache entry metadata is saved in a file with an extension .0, uncomment the following line if required
//String entryMetadata = Utils.readFile(new File(cacheDir, urlKey + ".0"));
// cached data is stored in the file with extension .1
String entryBody = IoUtils.readFile(new File(cacheDir, urlKey + ".1"));
if (!TextUtils.isEmpty(entryBody)) {
final PostModel[] postModels = mGson.fromJson(entryBody, PostModel[].class);
return Arrays.asList(postModels);
// Or if just a single object received, uncomment this
//return mGson.fromJson(entryBody, PostModel.class);
}
} catch (IOException e) {
Timber.w("Cannot read cache file:%s.1", urlKey);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment