Warm tip: This article is reproduced from stackoverflow.com, please click
android cache-control caching okhttp

(Android) OkHttpClient caching based on URLs (different caching for different urls)

发布于 2020-07-28 10:39:15

For Android Apps, is it possible to set different caching times for different urls using OkHttpClient?

for example, I have two urls:

  1. http://www.example.com/getcountries.php

  2. http://www.example.com/getnews.php

for the first url, i would like to set caching for 365 days:

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .maxStale(365, TimeUnit.DAYS)
        .build())
    .url("http://www.example.com/getcountries.php")
    .build();

for the second url, i would like to set caching for 3 minutes:

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .maxStale(3, TimeUnit.MINUTES)
        .build())
    .url("http://www.example.com/getnews.php")
    .build();

will it work? (with caching in place, debugging is difficult).

Thanks for your support.

Questioner
mooglife
Viewed
40
Jesse Wilson 2020-05-07 19:02

This will work but I think you want max-age and not max-stale. A cached response written at time a will be served until time b, a time that is derived from the response’s headers. The value you specify in max-stale is added to b to extend the lifetime of the cached response. The value you specify in max-age is added to a to constrain how long the cached response is valid.

https://square.github.io/okhttp/4.x/okhttp/okhttp3/-cache-control/-builder/