Retrofit 2.x的编辑:
在离线时,OkHttp拦截器是访问缓存的正确方法:
1)创建拦截器:
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;
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28;
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
}
2) 设置客户端:
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(httpCacheDirectory, cacheSize);
client.setCache(cache);
3) 将客户端添加到 Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
请查看
@kosiara - Bartosz Kosarzycki的
回答。您可能需要从响应中删除一些头信息。
OKHttp 2.0.x(请查看原始答案):
自OKHttp 2.0.x以来,HttpResponseCache
已更名为Cache
,setResponseCache
也更名为setCache
。因此,您应该像这样设置Cache
:
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
Cache cache = null;
try {
cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
Log.e("OKHttp", "Could not create http cache", e);
}
OkHttpClient okHttpClient = new OkHttpClient();
if (cache != null) {
okHttpClient.setCache(cache);
}
String hostURL = context.getString(R.string.host_url);
api = new RestAdapter.Builder()
.setEndpoint(hostURL)
.setClient(new OkClient(okHttpClient))
.setRequestInterceptor()
.build()
.create(MyApi.class);
最初的回答:
事实证明,服务器响应必须具有Cache-Control: public
才能使OkClient
从缓存中读取。
另外,如果您希望在网络可用时从网络请求,则应添加Cache-Control: max-age=0
请求头。 此答案显示了如何进行参数化设置。这就是我使用它的方式:
RestAdapter.Builder builder= new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if (MyApplicationUtils.isNetworkAvailable(context)) {
int maxAge = 60;
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
int maxStale = 60 * 60 * 24 * 28;
request.addHeader("Cache-Control",
"public, only-if-cached, max-stale=" + maxStale);
}
}
});
public
关键字才能使其离线工作。但是,这些标头不允许OkClient在有网络可用时使用网络。是否有任何方法可以设置缓存策略/策略以在有网络可用时使用网络? - osrl