我正在尝试使用 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);
这是带有 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
);
首先我在线请求并检查缓存文件。那里有正确的 JSON 响应和标头。但是当我尝试离线请求时,我总是得到 RetrofitError UnknownHostException
。我还应该做些什么来让 Retrofit 从缓存中读取响应吗?
编辑: 既然OKHTTP 2.0.x HttpResponseCache
Cache
setResponseCache
setCache
原文由 osrl 发布,翻译遵循 CC BY-SA 4.0 许可协议
为 Retrofit 2.x 编辑:
OkHttp 拦截器是离线访问缓存的正确方式:
1)创建拦截器:
2)设置客户端:
3)添加客户端进行改造
还要检查 @kosiara-Bartosz Kosarzycki 的 回答。您可能需要从响应中删除一些标头。
OKHttp 2.0.x(查看原答案):
因为OKHTTP 2.0.X
HttpResponseCache
Cache
setResponseCache
setCache
所以你应该setCache
像这样:原答案:
事实证明,服务器响应必须有
Cache-Control: public
才能使OkClient
从缓存中读取。此外,如果您想在可用时从网络请求,则应添加
Cache-Control: max-age=0
请求标头。 This answer 显示了如何对其进行参数化。这就是我使用它的方式: