okhttp 客户端何时缓存服务器响应?
Posted
技术标签:
【中文标题】okhttp 客户端何时缓存服务器响应?【英文标题】:when does okhttp client cache the server response? 【发布时间】:2017-05-30 09:32:37 【问题描述】:我在 java 中使用 okhttp 客户端 3.5.0 来缓存响应,服务器响应具有以下缓存控制标头:
缓存控制:私有,max-age=0,必须重新验证
首先我尝试进行实际的网络调用以获取服务器响应,然后在第二个请求中我想获取缓存的响应。
这是我的java代码:
HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(serverUrl).newBuilder();
HttpUrl httpUrl = httpUrlBuilder.build();
Request request = new Request.Builder()
.url(httpUrl)
.cacheControl(new CacheControl.Builder().maxAge(1, TimeUnit.DAYS).build())
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback()
@Override
public void onFailure(Call call, IOException e)
@Override
public void onResponse(Call call, final Response response) throws IOException
System.out.println("***************Response 1**************");
System.out.println("isSucess:"+response.isSuccessful());
Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response ::" +networkResponse);
);
Thread.sleep(5000);
Request request2 = new Request.Builder()
.cacheControl(new CacheControl.Builder().onlyIfCached().build())
.url(httpUrlBuilder.build())
.build();
call = okHttpClient.newCall(request2);
call.enqueue(new Callback()
@Override
public void onFailure(Call call, IOException e)
@Override
public void onResponse(Call call, final Response response) throws IOException
System.out.println("***********Response 2************");
System.out.println("isSucess:" +response.isSuccessful());
final Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response:" +networkResponse);
);
下面是第二个请求输出:(部分输出)
***********响应 2************
成功:假
缓存响应:null
网络响应:null
我是否遗漏了什么?
【问题讨论】:
【参考方案1】:除非您阅读并关闭响应正文,否则 OkHttp 不会缓存响应。这就是触发这些字节被下载和保存的原因。
try
if (response.cacheResponse() == null)
body.source().skip(Long.MAX_VALUE); // Exhaust response body.
finally
body.close();
【讨论】:
谢谢,杰西。但是服务器缓存控制头呢?我需要添加什么吗? 在 HTTP 服务器中设置其资源的缓存策略。您应该与服务器的维护人员确认缓存策略是否合适。以上是关于okhttp 客户端何时缓存服务器响应?的主要内容,如果未能解决你的问题,请参考以下文章