http缓存Android

来源:互联网 发布:王家卫我爱你知乎 编辑:程序博客网 时间:2024/06/06 03:54

mvp + rxjava2 + retrofit demo
https://github.com/wanglianghai/CacheHttpDemo/tree/master/app/src/main

//重新读取网络数据拦截器    Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {        @Override        public Response intercept(Chain chain) throws IOException {            //请求:无网络强制使用缓存            Request request = chain.request();            if (!NetConnect.isNetWorkConnect(MyApp.sContext)) {                request.newBuilder()                        .cacheControl(CacheControl.FORCE_CACHE)                        .build();            }            //给自己应用看的头            Response response = chain.proceed(request);            if (NetConnect.isNetWorkConnect(MyApp.sContext)) {                return response.newBuilder()                        .removeHeader("Pragma")                        .header("Cache-Control", "public ,max-age=0")                        .build();            } else {                int maxStale = 60 * 60 * 24 * 7;                return response.newBuilder()                        .removeHeader("Pragma")                        .header("Cache-Control", "public, only-if-cache, max-style=" + maxStale)                        .build();            }        }    };
//设置缓存的大小和url        File httpCacheFile = new File(MyApp.sContext.getCacheDir(), "responses"); // cache url        int cacheSize = 50 * 1024 * 1024; // 50 MiB        Cache cache = new Cache(httpCacheFile, cacheSize);        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)                .cache(cache).build();

其他的看git的demo 讲一下主要的拦截器

Created with Raphaël 2.1.0chain中得到网络请求request(未发起请求)是否有网络?从chain中得到网络回复的初始response(此时response里面还没数据)是否有网络?缓存响应时间为0,即不响应缓存直接吃网络获取数据(build后才开始拉数据(data))设置缓存过期时间(build后才开始拉数据(data))改造request请求(强制使用缓存)yesnoyesno

看不的no内容:改造request请求(强制使用缓存)