1

I use retrofit and picasso library. Picasso manages caching itself. But when I view logcat, I see log below. What does it mean? Doesn't the webservice and backend send cache info correctly? How can I solve this to make Retrofit cache correctly. So, Does this data make sense?

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Type: application/json
Date: Wed, 14 Dec 2016 07:15:48 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
OkHttp-Received-Millis: 1481597410805
OkHttp-Response-Source: NETWORK 200
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1481597409021
Pragma: no-cache
Server: Apache
Transfer-Encoding: chunked
Tabish Hussain
  • 852
  • 5
  • 13
hkaraoglu
  • 1,345
  • 1
  • 15
  • 34
  • 2
    About `Cache-Control`, please read http://stackoverflow.com/questions/7573354/what-is-the-difference-between-no-cache-and-no-store-in-cache-control – BNK Dec 14 '16 at 07:50

1 Answers1

2

You can set cache option to OkHttp with using Interceptor.

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new CachingControlInterceptor());
Retrofit restAdapter = new Retrofit.Builder()
        .client(client)
        .baseUrl(Constants.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

and CachingControlInterceptor is:

public class CachingControlInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    // Add Cache Control only for GET methods
    if (request.method().equals("GET")) {
        if (ConnectivityUtil.checkConnectivity(YaootaApplication.getContext())) {
            // 1 day
           request = request.newBuilder()
                    .header("Cache-Control", "only-if-cached")
                    .build();
        } else {
            // 4 weeks stale
           request = request.newBuilder()
                    .header("Cache-Control", "public, max-stale=2419200")
                    .build();
        }
    }

    Response originalResponse = chain.proceed(request);
    return originalResponse.newBuilder()
        .header("Cache-Control", "max-age=600")
        .build();
}
}

See this: https://stackoverflow.com/a/34401686/850347

Community
  • 1
  • 1
Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
  • This was exactly what I needed to get my squid server to recognize requests as needing to be cached for Fresco (via OkHttp)!!!!!!! – oddmeter Sep 14 '17 at 19:11