3

I am using retrofit2 to cash responses using cache interceptor

 @Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    if (NetworkUtil.isConnected(context)) {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, max-age=" + MAX_AGE)
                .build();
    } else {
        return originalResponse.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=" + MAX_STALE)
                .build();
    }
}

but i need to cache specific requests not all of it, how to do that?

Joel
  • 22,598
  • 6
  • 69
  • 93
Sahar
  • 301
  • 1
  • 6
  • You have your request in `Chain`, you can check url or what you need. – Cătălin Florescu Aug 02 '17 at 09:42
  • Not sure. But looking at https://speakerdeck.com/jakewharton/making-retrofit-work-for-you-ohio-devfest-2016 you add headers to your calls and then check the same in intercept and do what is required. Check slide 37 to 43 – Raghunandan Aug 02 '17 at 09:42
  • I there away to cache specific requests Internally without override "Cache-Control" header in the request sent to server? – Sahar Aug 03 '17 at 11:19

1 Answers1

2
public Response intercept(Chain chain)

The chain here contains the request that is being made.

public Response intercept(Chain chain) {
    Request request = chain.request()
}

You can inspect this request and act on the info, for example with request.url() and request.headers().

See more about intercepting here.

Tim
  • 41,901
  • 18
  • 127
  • 145
  • Thanks @Tim really helpful. – Sahar Aug 02 '17 at 10:44
  • I there away to cache specific requests Internally without override "Cache-Control" header in the request sent to server? – Sahar Aug 03 '17 at 11:16
  • @Sahar probably. See https://stackoverflow.com/questions/29119253/retrofit-okhttp-client-how-to-cache-the-response and other examples – Tim Aug 03 '17 at 11:19