我正在尝试使用 Retrofit 和 OkHttp 来实现缓存。这是我已经完成的:
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 客户端:
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
我的响应目录中有文件,但是当我尝试在没有互联网连接的情况下加载内容时,它给了我以下错误:
无法解析主机“example.com”:没有与主机名关联的地址
我只想将我的 http 响应存储在某处并在没有互联网连接的情况下加载它。
如果有互联网连接,我想重写缓存。