skip to content

In OkHttp, how does an application interceptor added with addInterceptor() differ from a network interceptor added with addNetworkInterceptor()?

level: middleimportance: must knowfreq 72%

answer

  1. where each sits in the chain
  2. redirects and cache hits
  3. original intent versus wire data
  4. chain.connection() is null for one

basics

~20 s

Application interceptors run once per call, see the app's original request and final response, and run for cache hits. Network interceptors run per network exchange, see redirects and OkHttp-added headers, get the Connection, and must call proceed() exactly once.

solid answer

~50 s

OkHttp builds one chain per call: your application interceptors first, then its own retry-and-redirect, header-bridging and cache stages, then the connect step, then your network interceptors, and finally the stage that writes to the socket. So an application interceptor runs **once per call**, sees the request as the app wrote it and the final response after redirects, runs even when the cache answers, and may short-circuit or call `proceed()` more than once. A network interceptor runs **once per network request**, so twice for one redirect, sees headers OkHttp added such as `Accept-Encoding: gzip`, is skipped for pure cache hits, can read `chain.connection()`, and must call `proceed()` exactly once on the same host and port. Since OkHttp 5.4.0 an application interceptor can also override client settings like the cache or DNS for one call; a network interceptor that tries throws.

code

kotlin · 19 lines
kotlin
import java.util.concurrent.TimeUnit
import okhttp3.Interceptor
import okhttp3.OkHttpClient

val client = OkHttpClient.Builder()
  // Application interceptor: runs once per call, even for cache hits.
  .addInterceptor { chain ->
    val request = chain.request()
    val slow = request.url.encodedPath.startsWith("/reports/")
    val next = if (slow) chain.withReadTimeout(30, TimeUnit.SECONDS) else chain
    next.proceed(request)
  }
  // Network interceptor: runs once per hop and can see the connection.
  .addNetworkInterceptor { chain ->
    val connection = chain.connection()
    println("${chain.request().url} via ${connection?.protocol()} to ${connection?.route()?.socketAddress}")
    chain.proceed(chain.request())
  }
  .build()

go deeper

for a junior

Recall the two builder methods and the headline difference: application interceptors run once per call, network interceptors once per network request.

for a middle

Explain the chain order and derive from it why redirects, cache hits, added headers and chain.connection() differ between the two kinds.

for a senior

Show judgment about placement: metrics on the wire versus per call, cache-header rewrites, and why faking or retrying in a network interceptor throws.

for a principal

Weigh the 5.4 per-call overrides against separate derived clients, knowing Retrofit 3 pulls OkHttp 4.12 unless the build pins a 5.x version.

## One chain, two insertion points Every OkHttp call runs through an ordered list of `Interceptor`s. Each one receives an `Interceptor.Chain`, may inspect or rewrite `chain.request()`, and calls `chain.proceed(request)` to hand the request to the next stage. In OkHttp 5 the list is assembled in this order: 1. **Application interceptors**, everything added with `addInterceptor()`. 2. **Retry and follow-up**: OkHttp's own stage that follows redirects, answers auth challenges and retries failed routes. 3. **Bridge**: turns the app's request into a network request by adding `Host`, `Connection`, `Accept-Encoding: gzip`, cookies and length headers, and undoes transparent gzip on the way back. 4. **Cache**: answers from the `Cache` when it can, or adds conditional headers such as `If-None-Match`. 5. **Connect**: obtains a connection from the pool or opens one. 6. **Network interceptors**, everything added with `addNetworkInterceptor()`. 7. **Call server**: writes the request to the socket and reads the response. Almost every difference between the two kinds follows from sitting above or below stages 2 to 5. ## What each kind sees | Question | Application interceptor | Network interceptor | |---|---|---| | How often does it run? | once per call | once per network request, so again for each redirect or retry | | Does it run for a pure cache hit? | yes | no, the network is never reached | | Which request does it see? | the app's original request | the request as transmitted, with OkHttp-added headers | | Which response does it see? | the final response after redirects | each intermediate response, such as a `301` | | `chain.connection()` | always `null` | the `Connection` carrying the request | | May it skip `proceed()`? | yes, it can return its own response | no | | May it call `proceed()` twice? | yes, after closing the first response | no, exactly once | OkHttp's interceptor guide shows the difference with one logging interceptor and a URL that redirects from `http` to `https`. Registered as an application interceptor it logs **once**, and the response's `request.url` differs from the original. Registered as a network interceptor it logs **twice**, one per hop, and each log line includes the connection's IP address, TLS cipher and protocol. ## Choosing where an interceptor goes The fence the library draws is about **intent versus wire**: - Put work that concerns the **app's intent** in an application interceptor: adding a header the app needs on every call, measuring the whole call including redirects, returning a synthetic response for a request that should never leave the device, or retrying the whole call. - Put work that concerns **what actually crosses the network** in a network interceptor: inspecting compressed traffic and the headers OkHttp added, recording which IP address and protocol served each hop, or rewriting a response header before the cache stage stores it. Two consequences catch people out: - A network interceptor rewriting a response's `Cache-Control` changes what the cache stores, because the cache stage sits above it. The same rewrite in an application interceptor happens after the cache has already decided. - A network interceptor is **not** a place to fake responses or retry: OkHttp throws an `IllegalStateException` if it skips `proceed()`, calls it twice, or changes the request's host or port. ## Overriding client settings per call From OkHttp 3.9 onward an application interceptor can change timeouts for one call with `chain.withConnectTimeout()`, `withReadTimeout()` and `withWriteTimeout()` and pass the returned chain's `proceed()`. **OkHttp 5.4.0** extended this to almost anything settable on `OkHttpClient.Builder`: `withCache()`, `withDns()`, `withConnectionPool()`, `withRetryOnConnectionFailure()` and others. Those overrides belong to the application side. In a network interceptor the connection has already been chosen, so in OkHttp 5.5 each of these overrides, the timeout ones included, throws an `IllegalStateException` explaining that the setting can't be adjusted in a network interceptor. Version matters on Android: Retrofit 3.0.0 still depends on OkHttp 4.12, which offers only the three timeout overrides. An app gets the 5.4 overrides only if its build resolves OkHttp 5.4 or later. ## A compact way to say it An application interceptor talks to OkHttp; a network interceptor talks to the server. The first sees one request and one answer per call, whatever OkHttp did in between. The second sees every exchange OkHttp actually performed, exactly as it went over the connection.

  • Why does a network interceptor see Accept-Encoding: gzip when the app never set it?
    OkHttp's bridge stage, which runs between the application interceptors and the network interceptors, adds `Accept-Encoding: gzip` when the request has no `Accept-Encoding` or `Range` header, and then decompresses the response transparently. The application interceptor sees the request before that stage and the decompressed response after it; the network interceptor sees the bytes as transmitted.
  • Your metrics interceptor reports far fewer network calls than the server logs. Which registration explains it?
    It is probably registered with `addInterceptor()`. An application interceptor runs once per call, so redirects, route retries and conditional cache revalidations inside that call are invisible to it, while the server sees each one. Count requests in a network interceptor, or use an `EventListener`, when the number on the wire is what matters.
  • What happens if a network interceptor calls chain.withCache(null) in OkHttp 5.5?
    It throws an `IllegalStateException` saying the cache can't be adjusted in a network interceptor. By the time a network interceptor runs, the cache stage has already decided, so OkHttp 5.4.0 limits such overrides to application interceptors, which can disable the cache for a single call this way.

An application interceptor is the customer at a shop counter: one order, one parcel handed back, even when the parcel came straight off the shelf. A network interceptor is the courier, who makes a trip for every leg, including detours to a new address, and never moves when the shelf already had the item.

  • A network interceptor runs once per call, however many redirects happen.
  • Network interceptors also run when the response comes straight from the cache.
  • An application interceptor sees the Accept-Encoding: gzip header OkHttp adds.
  • chain.connection() is available in every interceptor.
  • A network interceptor can return a canned response without calling proceed().

Assumes OkHttp 5.5; chain overrides beyond the three timeouts, such as withCache() and withDns(), arrived in 5.4.0, while OkHttp 4.12, which Retrofit 3.0.0 depends on, has only the timeout overrides.