我正在尝试使用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 …