Skip to content

//okhttp/okhttp3/Interceptor

Interceptor

[jvm]\ fun interface Interceptor

Observes, modifies, and potentially short-circuits requests going out and the corresponding responses coming back in. Typically interceptors add, remove, or transform headers on the request or response.

Implementations of this interface throw IOException to signal connectivity failures. This includes both natural exceptions such as unreachable servers, as well as synthetic exceptions when responses are of an unexpected type or cannot be decoded.

Other exception types cancel the current call:

  • For synchronous calls made with Call.execute, the exception is propagated to the caller.
  • For asynchronous calls made with Call.enqueue, an IOException is propagated to the caller indicating that the call was canceled. The interceptor’s exception is delivered to the current thread’s uncaught exception handler. By default this crashes the application on Android and prints a stacktrace on the JVM. (Crash reporting libraries may customize this behavior.)

A good way to signal a failure is with a synthetic HTTP response:

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  if (myConfig.isInvalid()) {
    return Response.Builder()
        .request(chain.request())
        .protocol(Protocol.HTTP_1_1)
        .code(400)
        .message("client config invalid")
        .body("client config invalid".toResponseBody(null))
        .build()
  }

  return chain.proceed(chain.request())
}

Types

Name Summary
Chain [jvm]
interface Chain
Companion [jvm]
object Companion

Functions

Name Summary
intercept [jvm]
abstract fun intercept(chain: Interceptor.Chain): Response