改进缓存404响应

时间:2017-12-02 13:46:16

标签: android caching retrofit okhttp3

我正在使用okhttp3的改造缓存,如本答案中所述: https://stackoverflow.com/a/23503804/6212796, 这是我的干预者

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (Utils.isNetworkAvailable(context)) {
            int maxAge = 60; // read from cache for 1 minute
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            return originalResponse.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }

http客户端:

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);

    File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(httpCacheDirectory, cacheSize);
    client.setCache(cache);

并且缓存工作正常,但是一旦我从服务器获得404响应,即使服务器再次生效,改进也会遇到此响应。

这是服务器开启时的日志: enter image description here

这是服务器关闭时的响应: enter image description here

当它再次出现时: enter image description here

1 个答案:

答案 0 :(得分:1)

我在OkHttp 3.10.0中有相同的错误。 我通过手动从缓存中删除响应来修复它。 我在okhttp3包中创建了类。 (很重要!)

package okhttp3;

import android.content.Context;

import java.io.File;


class CacheUtil {
    static void remove(Context context, Request request) {
        try {
        Cache cache = new Cache(new File(context.getCacheDir(), "responses"), (10 * 1024 * 1024));//your cache folder
        cache.remove(request);
        } catch (Exception e) {
        }
    }
}

可以将其添加到您的改造呼叫队列中,如下所示:

    call.enqueue(new Callback<City>() {
        @Override
        public void onResponse(Call<City> call, Response<City> response) {
            if(response.isSuccessful()) {
                //execute success code
            } else {
                if (response.code() == 404) {
                    CacheUtil.remove(context, response.raw().request());
                }
            }
        }

        @Override
        public void onFailure(Call<City> call, Throwable t) {
            //execute failure code
        }
    });

也可以像这样将其添加到拦截器(必须将其添加到OkHttpClient.Builder中):

new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == 404) {
            CacheUtil.remove(context, request);
        }
        return response;
    }
}

也许这会帮助别人。