5条回答 默认 最新
- KosmoSakura 2018-04-08 03:08关注
底层没研究过,我一般是这么使用的拦截器,你参考下:
1.创建对象
mOkHttpClient.newBuilder() .cache(cache)//缓存路径 .cookieJar(CookiesManager.getInstance()) .retryOnConnectionFailure(true) .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(300, TimeUnit.SECONDS) .writeTimeout(300, TimeUnit.SECONDS) .addNetworkInterceptor(cacheIntercepter)//网络拦截器 .build();
2.拦截器
//网络拦截器:设置缓存策略 private Interceptor cacheIntercepter = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //无网的时候强制使用缓存 if (!NetworkUtil.isConnected()) { ToastUtil.showShortMessage("网络不可用,开始加载本地缓存"); request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build(); } Response response = chain.proceed(request); //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置 if (NetworkUtil.isConnected()) { String cacheControl = request.cacheControl().toString(); return response.newBuilder() // .addHeader("TerminalCode", "android_app") // .addHeader("TerminalVersion", "v" + FrameWorkSetting.clientVersion) // .addHeader("TerminalSim", FrameWorkSetting.phoneMODEL) .header("Cache-Control", cacheControl) .removeHeader("Pragma") .build(); } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale return response.newBuilder() // .addHeader("TerminalCode", "android_app") // .addHeader("TerminalVersion", "v" + FrameWorkSetting.clientVersion) // .addHeader("TerminalSim", FrameWorkSetting.phoneMODEL) .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .removeHeader("Pragma") .build(); } } };
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报