简体   繁体   中英

get stale body on OkHttp 2.0

My webservice sends these headers:

Cache-Control: public, max-age=60, max-stale=86400

Now on my first call, this is the response:

  1. code = 200
  2. cacheResponse = null
  3. networkResponse = Response{code=200, ...}
  4. body = correctdata

The second call within a minute is:

  1. code = 200
  2. cacheResponse = Response{code=200, ...}
  3. networkResponse = null
  4. body = correctdata

Now, after a minute, I delete my webservice, and do another call. Now because of the max-stale header, I expect to be able to retrieve the cacheResponse, to show the old data. The response is this:

  1. code = 404
  2. cacheResponse = Response{code=200, ...}
  3. networkResponse = Response{code=404, ...}
  4. body = pagenotfounditem

Now the cacheResponse.body() returns null, so I can't use the old data, so crashes on String cb = cacheBody.string(); . A code sample is shown below:

        if(response.networkResponse() != null) {
            System.out.println("There is no cache, or cache is invalidated.");
            if(!response.isSuccessful()) {
                System.out.println("Call is not successful");
                if(response.cacheResponse() != null) {
                    System.out.println("There is a cache");
                    ResponseBody cacheBody = response.cacheResponse().body();
                    String cb = cacheBody.string();
                    System.out.println("cacheBody: " + cb); 
                    return cb;
                }
            }

        }
        ResponseBody body = response.body();
        if(body != null) {
            String b = body.string();
            System.out.println("body: " + b); 
            return b;               
        }

Is this behaviour intended, and if so, how can I get the cached response data?

Add this request header:

Cache-Control: max-stale=86400

That'll cause OkHttp to use the cache only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM