【发布时间】:2014-06-19 04:35:42
【问题描述】:
我正在尝试使用 Retrofit 和 OKHttp 来缓存 HTTP 响应。我关注了this gist,最后得到了这段代码:
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
【问题讨论】:
-
您调用的服务器是否使用适当的 Cache-Control 标头进行响应?
-
返回这个
Cache-Control: s-maxage=1209600, max-age=1209600不知道够不够。 -
似乎
public关键字需要在响应标头中才能使其脱机工作。但是,这些标头不允许 OkClient 在可用时使用网络。是否有设置缓存策略/策略以在可用时使用网络? -
我不确定您是否可以在同一个请求中执行此操作。您可以检查相关的 CacheControl 类和 Cache-Control 标头。如果没有这样的行为,我可能会选择发出两个请求,一个仅缓存的请求(only-if-cached),然后是一个网络(max-age=0)一个。
-
这是我想到的第一件事。我在 CacheControl 和 CacheStrategy 类中度过了几天。但是两个请求的想法没有多大意义。如果
max-stale + max-age被传递,它确实从网络请求。但我想设置 max-stale 一周。即使有可用的网络,它也会从缓存中读取响应。
标签: java caching retrofit okhttp offline-caching