我在使用 OkHttpClient 2.0 进行缓存时遇到问题。响应似乎完全忽略了 Cache-Control header 。这就是我设置客户端和缓存的方式。
OkHttpClient client = new OkHttpClient();
cache = new Cache(new File(Session.getInstance().getContext().getCacheDir(),"http"), 10 * 1024 * 1024);
client.setCache(cache);
client.setCookieHandler(CookieHandler.getDefault());
client.setConnectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
我相信缓存目录已正确创建。这是我在应用程序的/cache/http 目录中的日志中看到的内容。
libcore.io.DiskLruCache
1
201105
2
这就是我创建请求的方式。
Request mRequest = new Request.Builder().url(mUrl).get().build();
获取响应:
Response response = client.newCall(mRequest).execute();
使用curl时,标题如下。
< HTTP/1.1 200 OK
< Date: Fri, 27 Jun 2014 19:39:40 GMT
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< Cache-Control: no-transform, max-age=1800
< Content-Type: application/json
< Transfer-Encoding: chunked
OKHttp响应头如下。
Connection:Keep-Alive
Content-Type:application/json
Date:Fri, 27 Jun 2014 18:58:30 GMT
Keep-Alive:timeout=5, max=100
OkHttp-Received-Millis:1403895511337
OkHttp-Selected-Protocol:http/1.1
OkHttp-Sent-Millis:1403895511140
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
响应永远不会被缓存,并且调用 client.getCache().getHitCount() 总是给出 0。有人可以建议这里可能需要进行哪些更改才能使缓存正常工作吗?谢谢。
最佳答案
好吧,问题是我所有的 get 和 post 请求都使用 Authorization Bearer xxxx header 和 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html第 14.8 节指出这些请求不能被缓存。解决方案是根据以下内容在服务器上使用 s-maxage 而不是仅使用最大年龄:
When a shared cache (see section 13.7) receives a request containing an Authorization field, it MUST NOT return the corresponding response as a reply to any other request, unless one of the following specific exceptions holds:
If the response includes the "s-maxage" cache-control directive, the cache MAY use that response in replying to a subsequent request.
关于android - OkHttpClient 2.0 上的缓存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460889/