在我的 android 应用程序中,我使用 OkHttp 缓存来自服务器的响应。为此,我实现了如下代码
private class CacheInterceptor implements Interceptor {
Context mContext;
public CacheInterceptor(Context context) {
this.mContext = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.header(HEADER_MOBILE_OS, Constants.MOBILE_OS)
.header(HEADER_APP_VERSION, BuildConfig.VERSION_NAME)
.build();
Response response = chain.proceed(request);
if (!mShouldUpdateCache) {
response.newBuilder()
.header("Cache-Control", String.format("max-age=%d", CACHE_MAX_AGE)).build();
} else {
//update cache in this case
response.newBuilder()
.header("Cache-Control", "no-cache").build();
mShouldUpdateCache = false;
}
return response;
}
}
这是我的拦截器类,我将其设置为 OkClient,如下所示
okHttpClient.networkInterceptors().add(new CacheInterceptor(context));
File httpCacheDirectory = new File(context.getCacheDir(), "response_cache");
Cache cache = new Cache(httpCacheDirectory, CACHE_SIZE);
if (cache != null) {
okHttpClient.setCache(cache);
}
但问题是,当布尔值mShouldUpdateCache
变为真时,我必须更新缓存。现在我已经写了response.newBuilder().header("Cache-Control", "no-cache").build();
,但它既没有更新缓存也没有从服务器获取,我该如何解决这个问题?