OkHttp interceptors

Networking Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

Release builds log full request bodies, including passwords. What's the fix?

Options
Hint 1 of 1

Which builds need body logging?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Add HttpLoggingInterceptor only in debug builds, with BODY level

Correct. Release builds shouldn't log bodies or auth headers.

Why not the others?
  • B Switch it to a network interceptor. Still logs everything.
  • C Use Log.d instead of Log.i. Debug logs are still captured on release builds.
  • D Obfuscate with R8. R8 doesn't hide logged strings.

30-second answer

An interceptor sees each request and response and can change, retry or short-circuit them by calling chain.proceed(request). Application interceptors (addInterceptor) run once per call, even when the response comes from cache, and are good for auth headers and logging. Network interceptors (addNetworkInterceptor) run for each network request, including redirects, and see the real headers sent on the wire.

Practise saying it · 30 s. No recording, just a timer

Explain OkHttp interceptors.

Say your answer out loud, then check which of these points you covered:

  • Intercept and modify calls
  • Application: once per call
  • Network: per network hop
  • Order matters
  • Don't log bodies in release

Deep dive

Order matters: interceptors run in the order added, and the response comes back in reverse.

HttpLoggingInterceptor should log bodies only in debug builds.

Don't do heavy work in interceptors; they run on OkHttp's threads for every call.

Use an Authenticator, not an interceptor, to refresh tokens on 401.

An auth header interceptor Compile-checked · Kotlin 2.4.21
class AuthHeader(private val token: () -> String?) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        val request = token()?.let { chain.request().newBuilder().header("Authorization", "Bearer $it").build() }
            ?: chain.request()
        return chain.proceed(request)
    }
}

Common mistakes

  • Logging full bodies, including tokens, in release builds.
  • Refreshing tokens in an interceptor without coordination, causing a refresh storm.
  • Expecting an application interceptor to see redirects.

Senior take & follow-ups

Explain both kinds and give one correct use for each.

Follow-up questions

Think of your answer first, then open the hint.

  1. Which runs for cached responses?

    Show hint

    Application interceptors.

  2. Why use an Authenticator for 401?

    Show hint

    OkHttp calls it exactly when authentication is challenged and retries with its result.

Suggest a fix if something here is wrong or out of date.