自己实现okhttp缓存

缓存问题:

当我们需要实现网络请求缓存时,okhhttp已经帮我们实现好了,只需要在拦截器里面调用okhttp对应的方法设置一下

@Override
public Response intercept(Chain chain) throws IOException {

    Response originResponse = chain.proceed(chain.request());
    //设置缓存时间为60秒,并移除了pragma消息头,移除它的原因是因为pragma也是控制缓存的一个消息头属性
    return originResponse.newBuilder().removeHeader("pragma")
                    .header("Cache-Control","max-age=60").build();
    }

但是这样做有一个前提: 对于同一个网络请求,在不同是时间请求,url是不变的

1.对于后端, 有时候我们会在Head里面添加随机的可变的参数(例如:时间戳MD5加密)
2.这样即使是同一个网络请求,不同的时间访问,也会有不一样的参数,这样就需要我们自己简单实现缓存策略
缓存策略:

只要服务器返回的JSON不一样,及替换缓存文件

public class HttpInterceptor implements Interceptor {

    private final String TAG = HttpInterceptor.class.getSimpleName();

    // log日志
    private final StringBuilder logBuilder = new StringBuilder();

    /**********************************************************************************************/

    public HttpInterceptor() {
    }

    /**********************************************************************************************/

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        // 请求URL
        final String url = request.url().toString();

        // 下载文件
        boolean isDownload = ("1".equals(request.header("xDownload")));

        // 下载请求
        if (isDownload) {

            LogUtil.e(TAG, "intercept[下载apk] ==> url = " + url);

            Response proceed = chain.proceed(requestBuilder.build());
            return proceed
                    .newBuilder()
                    .body(proceed.body())
                    .build();
        }
        // 普通请求
        else {

            // 是否需要缓存
            boolean needCache = ("1".equals(request.header("xCached")));

            // 是否需要登录
            boolean needLogin = ("1".equals(request.header("xLogin")));

            // 自定义User-Agent
            requestBuilder.addHeader("User-Agent", "111");
            requestBuilder.addHeader("Cache-Control", "no-cache");

            // 开发环境
            if (BuildConfig.DEBUG) {
                logBuilder.delete(0, logBuilder.length());
                logBuilder.append("====> Http " + request.method() + " url = ")
                        .append(url)
                        .append('\n');
                logBuilder.append("====> Http header: xCached = ").append(needCache)
                        .append(", xLogin = ").append(needLogin)
                        .append('\n');

                // POST请求
                if ("POST".equalsIgnoreCase(request.method())) {
                    RequestBody requestBody = request.body();
                    if (requestBody instanceof FormBody) {
                        FormBody formBody = (FormBody) requestBody;
                        int size = formBody.size();
                        Map<String, String> map = new HashMap<>(size);
                        for (int i = 0; i < size; i++) {
                            map.put(formBody.name(i), formBody.value(i));
                        }

                        if (BuildConfig.DEBUG) {
                            logBuilder.append("====> Http Post Parameters = ")
                                    .append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
                                    .append('\n');
                        }
                    }
                }
            }

            // 需要登录
            if (needLogin) {
                String userId = "111";
                String token = "222";

                if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(token)) {
                    String nonce = DeviceUtil.getRandomString(16);
                    long timestamp = System.currentTimeMillis();
                    String sign = EncryptUtil.md5(userId + token + nonce + timestamp);

                    // 添加公共参数
                    HttpUrl httpUrl = request.url().newBuilder()
                            .addQueryParameter("userId", userId)
                            .addQueryParameter("nonce", nonce)
                            .addQueryParameter("timestamp", String.valueOf(timestamp))
                            .addQueryParameter("sign", sign)
                            .build();

                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userId);
                    map.put("nonce", nonce);
                    map.put("timestamp", timestamp + "");
                    map.put("sign", sign);

                    if (BuildConfig.DEBUG) {
                        logBuilder.append("====> Http Auth Parameters = ")
                                .append(new GsonBuilder().setPrettyPrinting().create().toJson(map))
                                .append('\n');
                    }

                    requestBuilder.url(httpUrl);
                }
            }

            Response response;
            try {
                response = chain.proceed(requestBuilder.build());

                if (needCache) {
                    LogUtil.e(TAG, "====> Net[网络正常, 需要缓存]");

                    ResponseBody responseBody = response.body();
                    String body = responseBody.string();

                    if (response.isSuccessful()) {
                        HttpResult httpResult = new Gson().fromJson(body, HttpResult.class);

                        // 请求成功,data不为null,写缓存
                        if (httpResult.getStatus() == 0 && !body.contains("\"data\":null")) {

                            // 1. 读取最近保存的缓存
                            List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
                            if (null != list && list.size() > 0) {

                                HttpJson cache = list.get(0);
                                if (null != cache && !cache.getJson().equals(body)) {
                                    LogUtil.e(TAG, "====> Net[网络正常, DATA存在,  缓存存在, JSON更新]");
                                    cache.setJson(body);
                                    DBManager.getHttpJsonDao().update(cache);
                                } else {
                                    LogUtil.e(TAG, "====> Net[网络正常, DATA存在,  缓存存在, JSON不变]");
                                }
                            } else {
                                LogUtil.e(TAG, "====> Net[网络正常, DATA存在, 缓存为空, JSON保存]");
                                HttpJson model = new HttpJson();
                                model.setUrl(url);
                                model.setJson(body);
                                DBManager.getHttpJsonDao().insert(model);
                            }

                            if (BuildConfig.DEBUG) {
                                logBuilder.append("====> Http response[web] = ").append(body);
                            }
                        } else {
                            LogUtil.e(TAG, "====> Net[网络正常, DATA为空]");

                            // 请求成功,data为null,读缓存,并重新构建response
                            List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
                            if (null != list && list.size() > 0) {
                                HttpJson cache = list.get(0);

                                if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
                                    body = cache.getJson();

                                    if (BuildConfig.DEBUG) {
                                        logBuilder.append("====> Http response[cache] = ").append(body);
                                    }
                                }
                            }
                        }

                    } else {
                        // 请求失败,读缓存,并重新构建response

                        List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
                        if (null != list && list.size() > 0) {
                            HttpJson cache = list.get(0);

                            if (null != cache && !TextUtils.isEmpty(cache.getJson())) {
                                body = cache.getJson();

                                if (BuildConfig.DEBUG) {
                                    logBuilder.append("====> Http response[cache] = ").append(body);
                                }
                            }
                        }
                    }
                    return response.newBuilder().body(ResponseBody.create(responseBody.contentType(), body)).build();

                } else {
                    LogUtil.e(TAG, "====> Net[网络正常, 不要缓存]");

                    if (true) {
                        ResponseBody responseBody = response.body();
                        String body = responseBody.string();

                        if (BuildConfig.DEBUG) {
                            logBuilder.append("====> Http response[web] = ").append(body);
                        }

                        return response.newBuilder().body(ResponseBody.create(responseBody.contentType(), body)).build();
                    } else {
                        return response;
                    }
                }
            } catch (Exception e) {
                LogUtil.e(TAG, e.getMessage(), e);

                if (needCache) {
                    LogUtil.e(TAG, "====> Net[网络异常, 需要缓存]");

                    // 请求失败,读缓存,并重新构建response
                    List<HttpJson> list = DBManager.getHttpJsonDao().queryBuilder().where(HttpJsonDao.Properties.Url.eq(url)).list();
                    if (null != list && list.size() > 0) {

                        HttpJson cache = list.get(0);

                        if (null != cache) {

                            String json = cache.getJson();

                            if (!TextUtils.isEmpty(json)) {
                                LogUtil.e(TAG, "====> Net[网络异常, 缓存存在, JSON存在]");

                                if (BuildConfig.DEBUG) {
                                    logBuilder.append("====> Http response[cache] = ").append(json);
                                }

                                // 重新构建 200 的请求
                                return new Response.Builder()
                                        .code(200)
                                        .message("OK, but from cache")
                                        .protocol(Protocol.HTTP_1_1)
                                        .request(request)
                                        .body(ResponseBody.create(MediaType.parse("application/json"), json))
                                        .build();
                            } else {
                                LogUtil.e(TAG, "====> Net[网络异常, 缓存存在, JSON为空]");
                            }
                        } else {
                            LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
                        }
                    } else {
                        LogUtil.e(TAG, "====> Net[网络异常, 缓存为空]");
                    }
                } else {
                    LogUtil.e(TAG, "====> Net[网络异常, 不要缓存]");
                }
                throw e;
            } finally {
                LogUtil.e(TAG, logBuilder.toString());
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容