我一直在尝试使用OkHttp和Retrofit来缓存http请求。但是我似乎无法弄清楚为什么它不起作用。
@Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=10000000")
@FormUrlEncoded
@POST("/news/getNewslist/")
void newsListByGenre(@Field("news_genre") String genre,
Callback<ArrayList<NewsStory>> callback);
这是其中一个请求,它包含了所有必需的头信息。此外,为了测试是否将内容写入文件缓存,我手动给OkHttpClient分配了一个缓存。
OkHttpClient name = new OkHttpClient();
try {
if (!cache.exists())
cache.createNewFile();
name.setResponseCache(new HttpResponseCache(cache,
10 * 1024 * 1024));
} catch (IOException e) {
e.printStackTrace();
}
我创建的文件缓存只有36个字节,所以我确定没有缓存任何内容。
我还尝试确保服务器具有所需的标头,尽管我希望它能在没有服务器干预的情况下工作,但我也在请求中设置了缓存控制标头。这是来自Retrofit的调试日志。
null: HTTP/1.1 200 OK
Cache-Control: public, max-age=360000
Connection: Keep-Alive
Content-Length: 5167
Content-Type: application/json
Date: Fri, 28 Jun 2013 01:00:22 GMT
Keep-Alive: timeout=5, max=99
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Android-Received-Millis: 1372381311315
X-Android-Response-Source: NETWORK 200
X-Android-Selected-Transport: http/1.1
X-Android-Sent-Millis: 1372381311048
X-Powered-By: PHP/5.4.7
我已经反复阅读了HTTP的缓存机制,但似乎我漏掉了一些东西。