Retrofit and OkHttp

Learn to build a production-ready Android networking layer using Retrofit and OkHttp with interceptors, timeouts, and proper error mapping in Kotlin. About 25 minutes.

Why it matters

  • Timeouts that are missing or wrong make screens spin for a long time on bad networks, or fail requests that would have finished.
  • Building a new OkHttpClient for each request or screen throws away connection reuse and creates extra thread and connection pools.
  • Handling 401 badly (no retry limit, refresh call going through the same authenticator) leads to refresh loops.
  • Interviewers test the OkHttp interceptor chain and the difference between HttpException and IOException to see if you understand what happens below the Retrofit interface.

The simple explanation

  • The API is a restaurant kitchen.
  • Retrofit is the waiter who takes your order and brings the food.
  • OkHttp is the kitchen staff and the delivery driver.
  • Interceptors are the quality control inspectors checking the food before it leaves or arrives.

Retrofit turns an annotated Kotlin interface into HTTP calls. At runtime it creates a dynamic proxy for the interface, reads the annotations, and uses a converter (kotlinx.serialization, Moshi, Gson) to turn bodies into objects. OkHttp does the actual transport: connection pooling, HTTP/2, TLS, redirects, retries on failed connections and caching.

Share one OkHttpClient across the app. Each client has its own connection pool and dispatcher, so a client per request or per screen means no connection reuse and a new TLS handshake for every call. If one call site needs different settings (for example a longer timeout for uploads), derive a client with okHttpClient.newBuilder(); the derived client shares the pool and dispatcher.

OkHttp has two interceptor layers:

TypeAdded withRunsTypical use
Application interceptoraddInterceptorOnce per call, even if the response comes from the cacheAuth header, logging, custom headers
Network interceptoraddNetworkInterceptorOnce per network request, including each redirect and retry; not for cache hitsObserving the exact bytes and headers on the wire, the connection used

OkHttp's default timeouts are 10 s for connect, read and write, and no limit for the whole call (callTimeout is 0). Read and write timeouts apply to each individual socket operation, so a server that sends a few bytes every few seconds can keep a call open for a long time; callTimeout caps the whole call.

A Retrofit suspend function is main-safe: Retrofit enqueues the call on OkHttp's own threads and resumes the coroutine with the result. If the coroutine is cancelled, Retrofit cancels the OkHttp call. There are two return styles:

Return typeOn 2xxOn non-2xxOn connection failure
suspend fun get(): UserReturns the bodyThrows HttpExceptionThrows IOException
suspend fun get(): Response<User>isSuccessful is true, body() holds the objectReturned normally; body() is null, read errorBody()Throws IOException

A body that cannot be parsed throws the converter's exception (SerializationException for kotlinx.serialization, JsonDataException for Moshi), which is neither an HttpException nor, in most cases, an IOException.

One request through Retrofit and OkHttp
One request through Retrofit and OkHttp The repository calls a suspend function on the Retrofit interface. Retrofit enqueues the call on OkHttp's own threads. The application interceptors run, then the network interceptors, and the request goes to the server. The response comes back the same way, the converter parses the body into a User, and the coroutine resumes with it. App interceptors, then network interceptors suspend getUser() ENQUEUE HTTP REQUEST HTTP RESPONSE RESPONSE BODY CONVERTER PARSES IT User, RESUMES Repository calls the API Retrofit interface proxy OkHttp HTTP client Server REST API
The suspend call is main-safe: Retrofit enqueues it on OkHttp's threads, interceptors run in order, and the converter turns the body into objects.

Notes

  • Provide one OkHttpClient and one Retrofit instance from DI. Use newBuilder() when a call site needs different settings; it shares the connection pool.
  • Add HttpLoggingInterceptor only in debug builds, and call redactHeader("Authorization") so tokens do not end up in logcat.
  • Set connectTimeout, readTimeout and writeTimeout deliberately, and add a callTimeout if you need an upper bound for the whole call. The defaults are 10 s, 10 s, 10 s and no call limit.
  • A suspend function returning T throws HttpException on non-2xx. Returning Response<T> gives you the status code without an exception; check isSuccessful before using body().
  • Application interceptors run once per call; network interceptors run once per network request, so a redirect runs them twice and a cache hit does not run them at all.
  • IOException means the request did not complete (no network, DNS failure, timeout, connection reset). HttpException means the server answered with a non-2xx status.
  • Parse failures are a third category. Map them separately; retrying will not fix a contract mismatch.
  • Do not wrap the call in a catch-all that swallows CancellationException. Catch the specific exceptions you map, or re-throw CancellationException first.

Code example

This shows one shared OkHttpClient with explicit timeouts and debug-only logging, a Retrofit service with both return styles, and a repository that maps each failure type to a sealed result.

import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.HttpException
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path
import java.io.IOException
import java.util.concurrent.TimeUnit
 
@Serializable
data class User(val id: Long, val name: String)
 
interface UserService {
    @GET("users/{id}")
    suspend fun getUser(@Path("id") id: Long): User // non-2xx throws HttpException
 
    @GET("users/{id}")
    suspend fun getUserResponse(@Path("id") id: Long): Response<User> // non-2xx is returned
}
 
// One client for the whole app; provide it as a singleton from DI.
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(20, TimeUnit.SECONDS)
    .writeTimeout(20, TimeUnit.SECONDS)
    .callTimeout(30, TimeUnit.SECONDS) // whole call; the default is no limit
    .apply {
        if (BuildConfig.DEBUG) { // needs buildFeatures { buildConfig = true }
            addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
                redactHeader("Authorization")
            })
        }
    }
    .build()
 
private val json = Json { ignoreUnknownKeys = true }
 
val userService: UserService = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .client(okHttpClient)
    .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
    .build()
    .create()
 
sealed interface NetworkResult<out T> {
    data class Success<T>(val data: T) : NetworkResult<T>
    data class HttpError(val code: Int) : NetworkResult<Nothing>
    data object NetworkError : NetworkResult<Nothing>
    data class ParseError(val cause: SerializationException) : NetworkResult<Nothing>
}
 
class UserRepository(private val api: UserService) {
    suspend fun fetchUser(id: Long): NetworkResult<User> =
        try {
            NetworkResult.Success(api.getUser(id))
        } catch (e: HttpException) {
            NetworkResult.HttpError(e.code()) // server answered 4xx or 5xx
        } catch (e: IOException) {
            NetworkResult.NetworkError // no connection, timeout, reset
        } catch (e: SerializationException) {
            NetworkResult.ParseError(e) // body did not match the model
        }
}
  • HttpException lives in retrofit2, not in OkHttp. It is only thrown for the bare User return type; getUserResponse would return the error response instead.
  • There is no catch-all Exception, so CancellationException passes through untouched and cancellation keeps working.
  • retrofit2.create is the reified Kotlin extension, so .create() needs no class argument.

Run the idea in plain Kotlin

This models OkHttp's interceptor chain: the application interceptor runs once, while the network interceptor runs once per network request, so a redirect runs it twice.

data class Request(val path: String, val headers: Map<String, String> = emptyMap())
data class Response(val code: Int, val location: String? = null)

fun interface Interceptor {
  fun intercept(request: Request, proceed: (Request) -> Response): Response
}

fun runChain(interceptors: List<Interceptor>, request: Request, last: (Request) -> Response): Response {
  fun step(i: Int, r: Request): Response =
      if (i == interceptors.size) last(r) else interceptors[i].intercept(r) { next -> step(i + 1, next) }
  return step(0, request)
}

// Pretend server: /old redirects to /new
fun server(r: Request): Response {
  println("  server: " + r.path + " auth=" + r.headers["Authorization"])
  return if (r.path == "/old") Response(301, location = "/new") else Response(200)
}

fun main() {
  var appCalls = 0
  var networkCalls = 0
  val app = listOf(Interceptor { r, proceed ->
      appCalls++
      println("app interceptor: " + r.path)
      proceed(r.copy(headers = r.headers + ("Authorization" to "Bearer abc")))
  })
  val network = listOf(Interceptor { r, proceed ->
      networkCalls++
      println("network interceptor: " + r.path)
      proceed(r)
  })
  // Follows redirects between the two layers, like OkHttp's RetryAndFollowUpInterceptor
  val followUps = Interceptor { r, _ ->
      var current = r
      var response = runChain(network, current, ::server)
      while (response.code in 300..399) {
          current = current.copy(path = response.location!!)
          response = runChain(network, current, ::server)
      }
      response
  }
  val result = runChain(app + followUps, Request("/old")) { error("unreachable") }
  println("final code: " + result.code)
  println("app interceptor calls: " + appCalls + ", network interceptor calls: " + networkCalls)
}

Expected output:

app interceptor: /old
network interceptor: /old
  server: /old auth=Bearer abc
network interceptor: /new
  server: /new auth=Bearer abc
final code: 200
app interceptor calls: 1, network interceptor calls: 2

In production

The Infinite Refresh Loop
  • Users reported the app becoming unresponsive after being logged in for a long time, with heavy traffic to the refresh endpoint.
  • The OkHttp Authenticator refreshed the token on every 401 and never gave up.
  • The refresh token itself had expired, and the refresh request went through the same client, so every refresh got a 401 that triggered another refresh.
The fix
  • Sent the refresh request through a separate client without the authenticator, so a 401 from the refresh endpoint is just a failed refresh.
  • In authenticate, returned null when the response already had a prior 401 (response.priorResponse), so each call retries at most once.
  • When the refresh fails with 401, cleared the session and sent the user to login.
Activity leaked by an interceptor
  • Memory grew over long sessions and LeakCanary reported a destroyed MainActivity still referenced.
  • A custom interceptor took a Context to read string resources, and it was created with the Activity as that context.
  • The interceptor was installed on the app-wide OkHttpClient, which lives as long as the process, so it kept the first Activity alive.
The fix
  • Passed applicationContext instead, through a small ResourceProvider interface provided by DI.
  • Kept the single client and interceptor in the DI singleton graph.
  • Confirmed with LeakCanary that the Activity was no longer retained after rotation and back navigation.

Common mistakes

  • Creating multiple OkHttpClient instances. Each instance has its own connection pool and dispatcher, so connections are not reused and every call pays for a new TCP and TLS handshake. Share one client and use newBuilder() for variants.
  • Swallowing CancellationException. A catch-all catch (e: Exception) that returns an error result turns cancellation into a fake failure, and the code after it keeps running (updating state, retrying) after the screen is gone.
  • Adding the auth header in a network interceptor. OkHttp removes Authorization when it follows a redirect to a different host; a network interceptor runs again for the redirected request and would put the token back, sending it to that other host. Add auth headers in an application interceptor.
  • Logging bodies and headers in release. HttpLoggingInterceptor at BODY or HEADERS prints tokens and personal data to logcat. Add it only in debug and redact Authorization.
  • Relying on default timeouts without thinking. The 10 s defaults may be too short for uploads and there is no limit on the whole call. Set the four timeouts for your traffic.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between an Application Interceptor and a Network Interceptor in OkHttp?”

“How do you handle a 401 Unauthorized error to refresh an access token?”

“Why should you avoid a catch-all catch (e: Exception) around a suspend network call?”

“What is the purpose of a connection pool in OkHttp?”

Quiz

Which interceptor type should you use to add a 'User-Agent' header to every outgoing request?

A coroutine is cancelled while a Retrofit suspend call is in progress, and your code wraps the call in catch (e: Exception) that returns an error result. What happens?

What is the main cost of creating a new OkHttpClient for every request?

A Retrofit function is declared as suspend fun getUser(): User (not Response<User>). What happens when the server returns 500?

0 of 4 answered

Mini task

Task: Implement a Secure Network Result Wrapper

  1. Create a sealed interface named NetworkResult<out T> with Success(val data: T), HttpError(val code: Int), NetworkError and ParseError subtypes.
  2. Create an interface ApiService with a single suspend function fetchData(): String annotated with @GET("test"), and register ScalarsConverterFactory (from converter-scalars) so Retrofit can return a plain String.
  3. Build one OkHttpClient with explicit connect, read, write and call timeouts, and HttpLoggingInterceptor only in debug with redactHeader("Authorization").
  4. Implement a Repository class that takes ApiService as a constructor parameter, with a function safeApiCall() that calls fetchData().
  5. Map HttpException to HttpError(e.code()) and IOException to NetworkError. Do not add a catch-all, or if you do, re-throw CancellationException first.
  6. Add a second function using Response<String> and map isSuccessful == false to HttpError(response.code()).

Done Condition: You have functions that return a NetworkResult, correctly distinguish a network failure from a server error in both return styles, and do not break coroutine cancellation.

Next: Ktor client