我试图为OkHttp设置缓存,所以它第一次尝试从服务器检索到一个响应,直到到期的头部日期,或来自服务器的缓存控制头,使响应失效从缓存.
目前,它缓存响应,但是在再次请求资源时不使用它.可能这不是应该被使用的方式.
我正在使用缓存设置OkHttpClient:
public static Cache createHttpClientCache(Context context) {
try {
File cacheDir = context.getDir("service_api_cache", Context.MODE_PRIVATE);
return new Cache(cacheDir, HTTP_CACHE_SIZE);
} catch (IOException e) {
Log.e(TAG, "Couldn't create http cache because of IO problem.", e);
return null;
}
}
这样使用:
if(cache == null) {
cache = createHttpClientCache(context);
}
sClient.setCache(cache);
这是我如何使用OkHttp向服务器发出一个实际上无法使用缓存的请求之一:
public static JSONObject getApi(Context context)
throws IOException, JSONException, InvalidCookie {
HttpCookie sessionCookie = getServerSession(context);
if(sessionCookie == null){
throw new InvalidCookie();
}
String cookieStr = sessionCookie.getName()+"="+sessionCookie.getValue();
Request request = new Request.Builder()
.url(sServiceRootUrl + "/api/"+API_VERSION)
.header("Accept", "application/json")
.header("Cookie", cookieStr)
.build();
Response response = sClient.newCall(request).execute();
if(response.code() == 200){
String charset = getResponseCharset(response);
if(charset == null){
charset = "utf-8";
}
String responseStr = new String(response.body().bytes(), charset);
response.body().close();
return new JSONObject(responseStr);
} else if(response.code() == 401){
throw new InvalidCookie();
} else {
return null;
}
}
如果我找到我指定为OkHttp的缓存的目录,我可以看到日志文件和其他4个包含某些请求的响应的文件.这个请求(我刚刚粘贴代码的/ api一个)存储在缓存目录中,因此它被真正缓存,但文件名最后有一个.tmp,就好像没有正确保存到最终文件像其他要求一样.
这是它的请求的服务器响应的标题如何:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Expires: Sat, 09 Aug 2014 19:36:08 GMT
Cache-Control: max-age=86400, must-revalidate
Last-Modified: Sun, 04 Aug 2013 15:56:04 GMT
Content-Length: 281
Date: Fri, 08 Aug 2014 19:36:08 GMT
而这是OkHttp如何将其存储在缓存中:
{HOST}/api/0.3
GET
0
HTTP/1.1 200 OK
9
Server: Apache-Coyote/1.1
Expires: Sat, 09 Aug 2014 19:36:08 GMT
Cache-Control: max-age=86400, must-revalidate
Last-Modified: Sun, 04 Aug 2013 15:56:04 GMT
Content-Length: 281
Date: Fri, 08 Aug 2014 19:36:08 GMT
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1407526495630
OkHttp-Received-Millis: 1407526495721
OkHttp创建此文件后,它不断向服务器请求相同的资源.我可以在Wireshark看到这些消息.
我究竟做错了什么?
更新:
这是Jesse建议后的服务器响应:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Expires: Thu, 14 Aug 2014 18:06:05 GMT
Last-Modified: Sun, 10 Aug 2014 12:37:06 GMT
Content-Length: 281
Date: Wed, 13 Aug 2014 18:06:05 GMT
更新2:
试了一下代码版本,发现很有可能有关于缓存的错误.这是我从Maven输出中得到的:
Results :
Failed tests:
CacheTest.conditionalHitUpdatesCache:1653 expected: but was:
Tests in error:
CallTest.tearDown:86 » IO failed to delete file: C:\Users\Adrian\AppData\Local...
Tests run: 825, Failures: 1, Errors: 1, Skipped: 17