使用Retrofit 2.0和okhttp3进行缓存 [英] Caching with Retrofit 2.0 and okhttp3
问题描述
我正在尝试使用Retrofit和OkHttp实现缓存.这是我已经完成的事情:
I'm trying to implement caching using Retrofit and OkHttp. Here what I've already done:
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder request = originalRequest.newBuilder();
Response response = chain.proceed(request.build());
return response.newBuilder()
.removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", "max-age=2419200")
.build();
}
};
@Provides
@Singleton
OkHttpClient provideHttpClient(Context context) {
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(httpCacheDirectory, cacheSize);
HttpLoggingInterceptor oggingInterceptor = new HttpLoggingInterceptor();
oggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(oggingInterceptor).build();
}
然后将这个拦截器添加到HTTP客户端:
And then I'm adding this interceptor to the HTTP client:
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
我的 response 目录中有文件,但是当我尝试在没有Internet连接的情况下加载内容时,会出现以下错误:
I've got files inside my responses directory, however when I try to load content without internet connection, it gives me the following error:
无法解析主机"example.com":没有与主机名关联的地址
我只想将http响应存储在某个地方,如果没有互联网连接就将其加载.
I just want to store my http response somewhere and load it if there are no internet connection.
如果存在Internet连接,我想重写缓存.
If there is an Internet connection, I want to rewrite cache.
推荐答案
以这种方式设置标头(恰好50000)解决了该问题.
Setting header this way (exactly 50000) solved the issue.
.header("Cache-Control", String.format("max-age=%d", 50000))
这篇关于使用Retrofit 2.0和okhttp3进行缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!