2
votes

I am using okhttp client 3.5.0 in java to cache the response and server response has below cache-control header:

Cache-Control: private, max-age=0, must-revalidate

First I am trying to make actual network call to get the server response, then in second request I want to get cached response.

Here is my java code:

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);

    }
});

And below is the second request output:(partial output)

***********Response 2************

isSucess:false

Cached Response:null

Network Response:null

Whether I am missing anything?

1

1 Answers

2
votes

OkHttp won’t cache a response unless you read and close the response body. This is what triggers those bytes to be downloaded and saved.

try {
  if (response.cacheResponse() == null) {
    body.source().skip(Long.MAX_VALUE); // Exhaust response body.
  }
} finally {
  body.close();
}