0
0
Android Kotlinmobile~5 mins

OkHttp interceptors in Android Kotlin

Choose your learning style9 modes available
Introduction

OkHttp interceptors let you watch and change network requests and responses. They help you add headers, log data, or handle errors easily.

Add a token or API key to every network request automatically.
Log request and response details for debugging your app.
Retry a request if it fails due to network issues.
Modify response data before your app uses it.
Block or redirect certain requests based on conditions.
Syntax
Android Kotlin
class MyInterceptor : Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    // Modify request if needed
    val response = chain.proceed(request)
    // Modify response if needed
    return response
  }
}

val client = OkHttpClient.Builder()
  .addInterceptor(MyInterceptor())
  .build()

The intercept function runs for every request.

Use chain.proceed(request) to continue the request and get the response.

Examples
This interceptor adds an Authorization header to every request.
Android Kotlin
class HeaderInterceptor : Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val newRequest = chain.request().newBuilder()
      .addHeader("Authorization", "Bearer mytoken")
      .build()
    return chain.proceed(newRequest)
  }
}
This interceptor prints request URL and response code to the console.
Android Kotlin
class LoggingInterceptor : Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    println("Sending request to ${request.url}")
    val response = chain.proceed(request)
    println("Received response with code ${response.code}")
    return response
  }
}
Sample App

This program creates an OkHttp client with a logging interceptor. It sends a GET request to https://httpbin.org/get. The interceptor prints the request URL and response code. Finally, it prints the length of the response body.

Android Kotlin
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response

class SimpleLoggingInterceptor : Interceptor {
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    println("Request URL: ${request.url}")
    val response = chain.proceed(request)
    println("Response code: ${response.code}")
    return response
  }
}

fun main() {
  val client = OkHttpClient.Builder()
    .addInterceptor(SimpleLoggingInterceptor())
    .build()

  val request = Request.Builder()
    .url("https://httpbin.org/get")
    .build()

  val response = client.newCall(request).execute()
  println("Response body length: ${response.body?.string()?.length}")
}
OutputSuccess
Important Notes

Interceptors run on a background thread, so avoid UI work inside them.

Use application interceptors for general tasks like adding headers.

Use network interceptors if you need to work with data after caching or retries.

Summary

OkHttp interceptors let you watch and change network requests and responses.

They are useful for adding headers, logging, retrying, or modifying data.

Create an interceptor by implementing the Interceptor interface and overriding intercept().