Retrofit 源码解读之离线缓存策略的实现 (2)

-然后,在拦截器内做Request拦截操作

Request request = chain.request(); if (!AppUtil.isNetworkReachable(UIUtils.getContext())) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .url(path).build(); UIUtils.showToastSafe("暂无网络"); }

其中,AppUtil.isNetworkReachable(UIUtils.getContext())是判断网络是否连接的方法,具体逻辑如下

/** * 判断网络是否可用 * * @param context Context对象 */ public static Boolean isNetworkReachable(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo current = cm.getActiveNetworkInfo(); if (current == null) { return false; } return (current.isAvailable()); }

在每个请求发出前,判断一下网络状况,如果没问题继续访问,如果有问题,则设置从本地缓存中读取

-接下来是设置Response

Response response = chain.proceed(request); if (AppUtil.isNetworkReachable(UIUtils.getContext())) { int maxAge = 60*60; // read from cache for 60 minute response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, max-age=" + maxAge) .build(); } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); }

先判断网络,网络好的时候,移除header后添加haunch失效时间为1小时,网络未连接的情况下设置缓存时间为4周

-最后,拦截器全部代码

Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (!AppUtil.isNetworkReachable(UIUtils.getContext())) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .url(path).build(); UIUtils.showToastSafe("暂无网络"); } Response response = chain.proceed(request); if (AppUtil.isNetworkReachable(UIUtils.getContext())) { int maxAge = 60 * 60; // read from cache for 1 minute response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, max-age=" + maxAge) .build(); } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); } return response; } };

快过年了,祝所有的童鞋们,身体健康,事事如意!!,咳咳,还有最重要的,程序无Bug!!!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwpgzx.html