Retrofit 2: Http Caching in Android

SHISHIR
3 min readMay 28, 2020

--

Caching is nothing but a way to store network fetched data on a device’s storage and access later when the device is offline or we want the same data again and again. Some image loading library like Picasso or Glide provide this caching when loading and displaying images but retrofit does not use this by default for its requests.

So in this article, you’ll learn the basics of caching and the way to enable online and offline caching in your Android app with Retrofit and Okhttp libraries.

Before starting lets know why caching is important…

Advantages of Caching

  • It reduces bandwidth consumption; therefore, it decreases network traffic and diminishes network congestion.
  • Saves you time you’d spend waiting for the server to get response.
  • If you need to access the same network resource again after having accessed it recently, your device won’t need to make a request to the server; it’ll get the cached response instead.

So Let’s start caching requests

Before starting, we will go through some important terms which are related to caching like: Okhttp, Interceptor, Cache-control, max-age, max-stale.

* Okhttp

This is the default HttpClient for Retrofit.

* Interceptors

Interceptor is a powerful component of this okhttp through which we can read and modify the requests and obviously, we will use this interceptor for our Cache control. There are two types of interceptor:

  • Application Interceptors — Gets you the final response.
  • Network Interceptors — To intercept intermediate requests.

For caching, we will use Network interceptor.

* Cache-control

Cache-control is an header used to specify caching policies in client requests and server responses. Inside the interceptors, we will to get the current request using chain.request() and add caching options to that request.

By the following way, we can add a “Cache-Control” header to the request: "public, only-if-cached, max-stale=60"

Then do a chain.proceed(request) to proceed with the modified request to return the response.

Find details for cache-control here.

* max-age = <seconds>

max-age is the oldest limit ( lower limit) till which the response can be returned from the cache. It takes value in seconds.

* max-stale = <seconds>

max-stale is the highest limit beyond which cache cannot be returned. It also takes value in seconds.

Step 1: Define a method to check for internet connectivity

We first need to have a method in our app that checks for Internet connectivity. May be you’re already familiar with it and want to take a look at it again:

Step 2: Create onlineInterceptor

Step 3: Create Offline Interceptor

Only if you want cache access when offline

Step 4: Create a cache object

Note: Cache size must be a Long

Step 5: Add interceptors and cache to an OKHTTPClient object

Step 6: Add the OKHTTPClient object to retrofit

DONE !

Always remember

  • Make sure you are using a GET request and not a POST!
  • Always make sure you add .removeHeader("Pragma").
  • Avoid using the HttpLoggingInterceptor while testing, it can cause some confusion in the beginning. Enable it in the end if you want.
  • ALWAYS ALWAYS ALWAYS delete your app from the device and reinstall it again upon every change in code, if you want to explore using Interceptors. Otherwise changing code while the old cache data is still on the device will cause you lots of confusion and misleading deductions!
  • The order of adding Interceptors to OKHTTPClient object matters!

Third Party Library

There is another library named OkCacheControl you can use for caching.

Finising

Maximum time we use the API for our app has a limit on the number of requests we can make, then this caching not only a helpful strategy to apply, but also something that is essential to keep working with the API. Plus, this is super useful when we want our users to access the data (response) from the same request when their device is offline too!

Thanks for reading the article. Be sure to give claps if you find this article helpful. Happy Android Coding :)

--

--

SHISHIR
SHISHIR

Written by SHISHIR

{ 'designation' : 'Lead Software Engineer' , 'hobby' : [ 'Music', 'Photography', 'Travelling' ] ,’email’: ‘shishirthedev@gmail.com’ }

Responses (4)