Discover how a simple interceptor can save you hours of repetitive coding and prevent hidden bugs!
Why OkHttp interceptors in Android Kotlin? - Purpose & Use Cases
Imagine you want to add a special note or check every letter you send in the mail manually. For every letter, you open it, write the note, check the address, and then send it. This takes a lot of time and you might forget or make mistakes.
Doing these checks and changes manually for every network request is slow and error-prone. You might forget to add important headers or log the request details, causing bugs or security issues. It's like repeating the same task over and over without a shortcut.
OkHttp interceptors act like a smart assistant who automatically checks and modifies every letter before it goes out or after it comes in. You write the rules once, and the interceptor applies them to all requests and responses, saving time and avoiding mistakes.
val request = originalRequest.newBuilder().addHeader("Auth", token).build()
val response = client.newCall(request).execute()val interceptor = Interceptor { chain ->
val newRequest = chain.request().newBuilder().addHeader("Auth", token).build()
chain.proceed(newRequest)
}
client = OkHttpClient.Builder().addInterceptor(interceptor).build()It enables automatic, consistent handling of network requests and responses, making your app more reliable and easier to maintain.
For example, an app can automatically add login tokens to every request or log errors centrally without changing each network call in the code.
Manual request handling is repetitive and error-prone.
Interceptors automate request and response processing.
This leads to cleaner, safer, and more maintainable network code.
Practice
Solution
Step 1: Understand the role of interceptors
OkHttp interceptors allow you to watch and change network requests and responses before they are sent or after they are received.Step 2: Compare with other options
The other options relate to managing database transactions, creating UI components dynamically, and handling user input events, which are unrelated to network interception.Final Answer:
To observe and modify network requests and responses -> Option BQuick Check:
Interceptor purpose = Observe and modify network calls [OK]
- Confusing interceptors with UI or database components
- Thinking interceptors handle user input
- Assuming interceptors manage app navigation
Solution
Step 1: Check the interface implementation
OkHttp interceptors implement the Interceptor interface and override the intercept() method with the correct signature.Step 2: Validate method signature and return type
The intercept method must take Interceptor.Chain and return a Response object, as shown in class MyInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { return chain.proceed(chain.request()) } }.Final Answer:
Correct interceptor implementation with override and proper method signature -> Option CQuick Check:
Interceptor class implements Interceptor interface [OK]
- Not implementing Interceptor interface
- Wrong method signature or missing return type
- Using unrelated interfaces like Runnable
class UserAgentInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val newRequest = chain.request().newBuilder()
.header("User-Agent", "MyAppAgent")
.build()
return chain.proceed(newRequest)
}
}Solution
Step 1: Analyze header modification
The interceptor creates a new request builder from the original request and sets the "User-Agent" header explicitly to "MyAppAgent".Step 2: Understand header effect
Setting the header with .header() replaces any existing "User-Agent" header with the new value.Final Answer:
"User-Agent" header is set to "MyAppAgent" in the outgoing request -> Option AQuick Check:
Header set by interceptor = "MyAppAgent" [OK]
- Assuming header is appended instead of replaced
- Thinking default headers remain unchanged
- Confusing compile errors with runtime behavior
class LoggingInterceptor : 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}")
}Solution
Step 1: Check method return type
The intercept method must return a Response object, but this code does not return anything.Step 2: Verify other code parts
Method name and usage of println are valid; request creation is correct.Final Answer:
Missing return statement for the Response object -> Option AQuick Check:
intercept() must return Response [OK]
- Forgetting to return the response
- Renaming intercept method incorrectly
- Thinking println is disallowed in intercept
Solution
Step 1: Understand retry logic in intercept()
Retries must happen inside intercept() by calling chain.proceed(request) multiple times if needed.Step 2: Evaluate options for retry implementation
Override intercept() to loop up to 3 times calling chain.proceed(request) until response.code != 500 or max retries reached correctly loops and retries up to 3 times checking response code. The other options do not implement retry correctly or rely on unsupported mechanisms.Final Answer:
Loop inside intercept() to retry request up to 3 times on 500 response -> Option DQuick Check:
Retry logic = loop in intercept() calling chain.proceed() [OK]
- Trying to retry outside intercept() method
- Assuming headers control retry automatically
- Throwing exceptions to trigger retry without handling
Ready to prove it?
Pass the test and this pattern moves unknown
