OkHttp interceptors let you watch and change network requests and responses. They help you add headers, log data, or handle errors easily.
OkHttp interceptors in 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.
class HeaderInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val newRequest = chain.request().newBuilder() .addHeader("Authorization", "Bearer mytoken") .build() return chain.proceed(newRequest) } }
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 } }
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.
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}") }
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.
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().