最佳答案
我试图使用 Revifit & 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);
这是带缓存控制头的 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
);
首先,我在线请求并检查缓存文件。这里有正确的 JSON 响应和头文件。但是当我尝试离线请求时,我总是得到 RetrofitError UnknownHostException
。还有什么我应该做的,使逆转修复读从缓存的响应?
编辑:
因为 OKHttp 2.0.x HttpResponseCache
是 Cache
,所以 setResponseCache
是 setCache