我想要与OkHttp改装使用缓存时是没有互联网.
我准备好OkHttpClient,如下所示:
RestAdapter.Builder builder= new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if (MyApplicationUtils.isNetworkAvaliable(context)) {
int maxAge = 60; // read from cache for 1 minute
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
request.addHeader("Cache-Control",
"public, only-if-cached, max-stale=" + maxStale);
}
}
});
并设置缓存如下所示:
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);
}
我检查了根设备,在缓存目录中保存文件与“响应头”和Gzip文件.
但是我在离线时没有得到改装缓存的正确答案,尽管在GZip文件中是我的正确答案.那么如何使Retrofit可以读取GZip文件,他如何知道应该是哪个文件(因为我有几个文件与其他响应)?
我公司里有simlar问题:)
问题出在服务器端.在serwer答复我有:
Pragma: no-cache
所以当我删除这一切都开始工作.在我删除之前,我得到所有的时间这样的例外:504不满意的请求(only-if-cached)
好的,我的身边如何执行.
OkHttpClient okHttpClient = new OkHttpClient();
File httpCacheDirectory = new File(appContext.getCacheDir(), "responses");
Cache cache = new Cache(httpCacheDirectory, maxSizeInBytes);
okHttpClient.setCache(cache);
OkClient okClient = new OkClient(okHttpClient);
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setEndpoint(endpoint);
builder.setClient(okClient);
如果您在测试中遇到问题(服务器或应用程序).您可以使用这样的功能来设置从服务器接收的头文件.
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()
.removeHeader("Pragma")
.header("Cache-Control",
String.format("max-age=%d", 60))
.build();
}
};
并添加它:
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
感谢你,因为你可以看到我能够删除Pragma:无缓存标头的测试时间.
另外我建议你阅读关于Cache-Control标题:
max-age , max-stale
其他有用的链接:
List of HTTP header fields
Cache controll
Another sample code
http://stackoverflow.com/questions/31321963/how-retrofit-with-okhttp-use-cache-data-when-offline