Skip to main content

How to enable caching in OKHTTP in Kotlin Android

How to enable caching in OKHTTP in Kotlin Android.

Here's a step-by-step tutorial on how to enable caching in OkHttp in Kotlin for Android:

Step 1: Add OkHttp to your project

To get started, you'll need to add the OkHttp library to your project. You can do this by adding the following dependency to your app-level build.gradle file:

implementation 'com.squareup.okhttp3:okhttp:4.9.1'

Step 2: Create an OkHttp client with a cache

In order to enable caching, we need to create an instance of the OkHttp client with a cache. You can do this by creating a new OkHttpClient.Builder object and calling the cache() method with a cache object.

Here's an example:

val cacheSize = 10 * 1024 * 1024 // 10 MiB
val cache = Cache(context.cacheDir, cacheSize.toLong())

val client = OkHttpClient.Builder()
.cache(cache)
.build()

In the above code, we create a cache object with a specified cache directory and size. We then pass this cache object to the cache() method of the OkHttpClient.Builder.

Step 3: Add cache-control headers to your requests

To take advantage of the caching mechanism, you need to add appropriate cache-control headers to your requests. This tells the server how to handle the caching of the response.

You can do this by creating a new Request object and adding the cache-control header using the Request.Builder. Here's an example:

val request = Request.Builder()
.url("https://api.example.com/data")
.header("Cache-Control", "public, max-age=86400") // Cache response for 24 hours
.build()

In the above code, we set the cache-control header to "public, max-age=86400", which instructs the server to cache the response for 24 hours.

Step 4: Enable response caching

To enable caching for responses, you need to add an interceptor to your OkHttpClient. This interceptor will be responsible for intercepting the response and storing it in the cache.

Here's an example:

val cacheInterceptor = object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalResponse = chain.proceed(chain.request())
val cacheControl = originalResponse.header("Cache-Control")

if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=86400") // Cache response for 24 hours
.build()
} else {
return originalResponse
}
}
}

val client = OkHttpClient.Builder()
.cache(cache)
.addNetworkInterceptor(cacheInterceptor) // Add the cache interceptor
.build()

In the above code, we create a cache interceptor that checks the cache-control header of the response. If the response does not have cache-control headers or contains headers that indicate the response should not be cached, we modify the response to include the cache-control header for caching.

Step 5: Use the OkHttp client for your requests

Now that you have enabled caching in OkHttp, you can use the client object to make your HTTP requests. Here's an example of making a GET request:

val request = Request.Builder()
.url("https://api.example.com/data")
.build()

client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle failure
}

override fun onResponse(call: Call, response: Response) {
// Handle response
}
})

In the above code, we create a newCall object using the client and enqueue it with a callback to handle the response.

That's it! You have successfully enabled caching in OkHttp in Kotlin for Android. Now, OkHttp will automatically cache the responses based on the cache-control headers you set in your requests, improving the performance and reducing network usage of your app.