根据
1.9.0使用的
OkClient翻新版不支持缓存。我们必须使用
OkHttpClientSquare
OkHttpClient库的实例。
你可以通过编译
compile 'com.squareup.okhttp:okhttp:2.3.0'
在一切翻新之前,都通过响应标头来缓存
Cache-Control:max-age=120,only-if-cached,max-stale
** 120是秒。
您可以在此处阅读有关标题的更多信息。
缓存头通常由服务器响应指示。 尝试在服务器中实现缓存头。 如果您没有选择,可以进行改装。
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .header("Cache-Control", String.format("max-age=%d, only-if-cached, max-stale=%d", 120, 0)) .build(); }};缓存位置:
private static void createCacheForOkHTTP() { Cache cache = null; cache = new Cache(getDirectory(), 1024 * 1024 * 10); okHttpClient.setCache(cache);}// returns the file to store cached detailsprivate File getDirectory() { return new File(“location”);}将拦截器添加到OkHttpClient实例:
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
最后将OkHttpClient添加到RestAdapter中:
RestAdapter.setClient(new OkClient(okHttpClient));
您可以浏览此幻灯片以获取更多参考。



