我正在尝试使用Retrofit和OKHttp来缓存HTTP响应.我按照这个要点,结束了这段代码:
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
HttpResponseCache httpResponseCache = null;
try {
httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
Log.e("Retrofit", "Could not create http cache", e);
}
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);
api = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient(okHttpClient))
.build()
.create(MyApi.class);
Run Code Online (Sandbox Code Playgroud)
这是带有Cache-Control标头的MyApi
public interface MyApi {
@Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200")
@GET("/api/v1/person/1/")
void requestPerson(
Callback<Person> callback
);
Run Code Online (Sandbox Code Playgroud)
首先,我在线请求并检查缓存文件.有正确的JSON响应和标题.但是当我尝试离线请求时,我总是得到RetrofitError UnknownHostException.我还有什么办法让Retrofit从缓存中读取响应吗?
编辑:
因为OKHttp 2.0.x HttpResponseCache是Cache …
我已经阅读了很多关于我的问题的问题和答案,但我仍然无法理解如何解决它。
我需要从服务器获取响应并将其存储在缓存中。之后,当设备离线时,我想使用缓存响应。当设备在线时,我想从服务器准确获取响应。
看起来没那么复杂。
这是我尝试这样做的方式(代码示例):
1)创建缓存的方法
Cache provideOkHttpCache() {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(this.getCacheDir(), cacheSize);
return cache;
}
Run Code Online (Sandbox Code Playgroud)
2)创建一个拦截器来修改缓存控制头
Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
CacheControl.Builder cacheBuilder = new CacheControl.Builder();
cacheBuilder.maxAge(0, TimeUnit.SECONDS);
cacheBuilder.maxStale(365, TimeUnit.DAYS);
CacheControl cacheControl = cacheBuilder.build();
Request request = chain.request();
if (isOnline()) {
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}
okhttp3.Response originalResponse = chain.proceed(request);
if (isOnline()) {
int maxAge = 20; …Run Code Online (Sandbox Code Playgroud)