我正在尝试创建一个Android应用,该应用将使用Retrofit从互联网获取数据。我也做了改造缓存系统。自应用程序离线以来,我可以正常工作24小时,但是24小时后,所有存储的缓存数据都会自行过期。 我什至将内部代码的到期时间从 60 * 60 * 20(1天)更改为 60 * 60 * 24 * 185(185天)。有什么解决办法吗?
public class RetrofitInstance {
private static final String BASE_URL = "DOMAIN_HERE";
public static Retrofit getRetrofit(Context context)
{
File httpCacheDirectory = new File(context.getCacheDir(), "httpCache");
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient httpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(chain -> {
try {
return chain.proceed(chain.request());
} catch (Exception e) {
Request offlineRequest = chain.request().newBuilder()
.header("Cache-Control", "public, only-if-cached," +
"max-stale=" + 60 * 60 * 24 * 185)
.build();
return chain.proceed(offlineRequest);
}
})
.build();
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(new Gson()))
.client(httpClient)
.baseUrl(BASE_URL)
.build();
}
}
答案 0 :(得分:0)
希望这会有所帮助。 1)尝试强制执行Cache-control
.cacheControl(CacheControl.FORCE_CACHE)
之后
Request offlineRequest = chain.request().newBuilder()
或 2)
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder()
.maxStale(365, TimeUnit.DAYS)
.build();
文档:https://square.github.io/okhttp/3.x/okhttp/okhttp3/Cache.html