我正在尝试为改造设置缓存,以便它不必不断检索数据。我遵循了这个SO,因为它似乎在我需要的正确方向上。
我有以下内容(与销售订单相同)
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10*1024*1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
client.setCache(cache);
但是,client.setCache(缓存)
返回错误无法解析方法setCache
。
我在这里做错了什么?我有改造2.1.0和okhttp3 3.4.1
在3. x中,OkHttpClient
上的一堆方法被移动到OkHttpClient.Builder
上的方法中。您需要这样的东西:
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10*1024*1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
File httpCacheDirectory = new File(getCacheDir(), "responses");
int cacheSize = 10*1024*1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
/////////and
public static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (Global.networkConnection()) {
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();
}
}
};