Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 104 ยท Networking

Networking with Retrofit and OkHttp

Call REST APIs from Android with Retrofit and OkHttp: interface definitions, suspend functions, interceptors, timeouts, base URLs and the Ktor alternative.

Most apps talk to a server: they log a user in, load a feed, upload a photo. On Android the long-standing standard for REST calls is the pair OkHttp and Retrofit. OkHttp is the HTTP client: connections, TLS, timeouts, caching and retries. Retrofit sits on top and turns an annotated Kotlin interface into a working API client, so a network call looks like a normal suspend function.

This lesson covers declaring an API, building the client, interceptors, timeouts and the Ktor client as an alternative. Real HTTP needs a device or emulator with network access, so the Retrofit code is read-only. The TryIt blocks are Kotlin stand-ins: a fake server, an API service that builds requests from a description, and an interceptor chain that behaves like OkHttp's. Each says what is real and what is the stand-in.

Declaring the API

With Retrofit you describe the endpoints and the library writes the implementation at runtime:

Kotlin
// read-only example: needs Retrofit
interface ShopApi {
    @GET("products")
    suspend fun products(
        @Query("category") category: String? = null,
        @Query("page") page: Int = 1
    ): List<ProductDto>

    @GET("products/{id}")
    suspend fun product(@Path("id") id: Long): ProductDto

    @POST("orders")
    suspend fun placeOrder(@Body order: OrderRequest): OrderDto

    @DELETE("orders/{id}")
    suspend fun cancelOrder(@Path("id") id: Long): Response<Unit>
}

The annotation gives the HTTP method and path, @Path fills a placeholder, @Query adds ?category=..., and @Body serializes an object as the request body. Because the functions are suspend, Retrofit runs the request on its own threads and resumes your coroutine with the result, so calling it from viewModelScope is main-safe. Return the body type directly and Retrofit throws HttpException for 4xx and 5xx responses, or return Response<T> to inspect the status code and headers yourself. Network trouble throws IOException. The types like ProductDto are plain data classes, covered in JSON with kotlinx.serialization and Moshi.

Building the client

Kotlin
// read-only example: needs Retrofit and OkHttp
val okHttp = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(20, TimeUnit.SECONDS)
    .writeTimeout(20, TimeUnit.SECONDS)
    .callTimeout(40, TimeUnit.SECONDS)
    .addInterceptor(AuthInterceptor(tokenProvider))
    .addInterceptor(HttpLoggingInterceptor().apply {
        level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
                else HttpLoggingInterceptor.Level.NONE
    })
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/v1/")
    .client(okHttp)
    .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
    .build()

val shopApi: ShopApi = retrofit.create(ShopApi::class.java)

Four details are worth knowing:

  • The base URL must end with a slash. Paths in the annotations are resolved against it, and a path starting with / replaces the whole path of the base URL, so "/products" would drop /v1/.
  • Create one OkHttpClient and one Retrofit for the app. They hold connection pools and threads; building one per request throws away the reuse. Dependency injection (see Hilt) is the usual way to share them.
  • Timeouts have layers. connectTimeout covers establishing the connection, readTimeout and writeTimeout are per read or write operation (a slow trickle of bytes keeps resetting them), and callTimeout caps the whole call. Defaults are 10 seconds for the first three and none for callTimeout.
  • A converter turns bytes into objects. Without a converter factory only ResponseBody and RequestBody work.

Your manifest also needs <uses-permission android:name="android.permission.INTERNET"/>. Since Android 9, plain http:// is blocked unless a network security config allows it, so use HTTPS.

The first TryIt is a stand-in for the API layer. A fake server returns canned Response objects for method-and-path pairs, and ShopApi turns Kotlin calls into Request objects the way Retrofit's annotations do, including the base-URL joining rule.

Kotlin An API interface and a fake server (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The stand-in builds requests by hand; real Retrofit reads annotations through reflection, handles encoding of paths and queries, and sends bytes over a real socket.

Interceptors

An interceptor is code that wraps every call. It can read or change the outgoing request, call chain.proceed(request) to continue and then read or change the response. Typical jobs are adding an auth header, logging, adding a user-agent and retrying:

Kotlin
// read-only example: needs OkHttp
class AuthInterceptor(private val tokens: TokenProvider) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .header("Authorization", "Bearer ${tokens.current()}")
            .build()
        return chain.proceed(request)
    }
}

Requests are immutable, so you always create a new one with newBuilder(). There are two kinds of interceptors: application interceptors (addInterceptor) see the call once, even when OkHttp follows redirects or retries, and network interceptors (addNetworkInterceptor) see each network hop including redirects, which is where you would log raw headers. Order matters: interceptors run in the order you add them on the way out and in reverse on the way back. Put the logging interceptor last in debug builds so it prints the request after the auth header has been added.

Never log request bodies or Authorization headers in release builds. Logs are readable by anyone with a debugging cable on an unlocked phone and by crash reporters.

flowchart LR
    APP["Your call"] --> A["AuthInterceptor"]
    A --> L["LoggingInterceptor"]
    L --> NET["Network"]
    NET -->|"response"| L
    L -->|"response"| A
    A -->|"response"| APP

Each interceptor can act on the way out and on the way back.

The second TryIt is a stand-in for OkHttp's chain. Each interceptor receives a Chain, may modify the request and calls proceed. One interceptor retries on server errors and the call wrapper enforces a timeout with withTimeout, the coroutine equivalent of callTimeout.

Kotlin Interceptor chain and timeouts (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the stand-in the timeout is one overall limit. OkHttp's separate connect, read and write timeouts are finer, but callTimeout works like this one.

Retrofit versus Ktor client

Retrofit is Android and JVM only. Ktor client is the Kotlin Multiplatform alternative: it has no annotation magic, you write requests in a Kotlin DSL, and it can run on top of OkHttp on Android:

Kotlin
// read-only example: needs Ktor client
val client = HttpClient(OkHttp) {
    install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    install(HttpTimeout) { requestTimeoutMillis = 30_000 }
}

suspend fun product(id: Long): ProductDto =
    client.get("https://api.example.com/v1/products/$id").body()

Choose Retrofit for an Android-only app where the interface style and the huge ecosystem help. Choose Ktor when you share networking code with iOS or the desktop. The rest of the app, repositories, ViewModels and error handling, looks the same either way, as shown in Error Handling and Offline-first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must be true of the string you pass to Retrofit.Builder().baseUrl()?

    Retrofit resolves endpoint paths relative to the base URL, and it requires the base to end with / so relative paths append to it correctly.
  2. 2. What does a suspend function in a Retrofit interface do when the server returns 404 and the return type is the body type?

    For non-2xx responses Retrofit throws HttpException when you ask for the body directly. Return Response<T> if you want to inspect the code yourself. Network failures throw IOException.
  3. 3. Why do interceptors create a new Request with newBuilder()?

    OkHttp requests are immutable, so you copy one into a builder, change what you need and pass the new request to chain.proceed.
  4. 4. Which timeout limits the total time of a whole call, including all reads and writes?

    connect, read and write timeouts apply to individual steps. Only callTimeout caps the entire call from start to finish.
  5. 5. When is Ktor client a better choice than Retrofit?

    Ktor client is multiplatform. Retrofit is JVM and Android only, which is fine for an Android-only app.

Summary

  • OkHttp is the HTTP engine; Retrofit turns an annotated interface (@GET, @POST, @Path, @Query, @Body) into suspend-function calls.
  • Share one OkHttpClient and one Retrofit; the base URL must end with /; add a converter factory for JSON.
  • Non-2xx responses throw HttpException (or return Response<T>), connection problems throw IOException.
  • Interceptors wrap every call for auth headers, logging and retries; application and network interceptors differ in what they see.
  • Set connect, read, write and call timeouts on purpose and never log secrets in release builds.
  • Ktor client is the multiplatform alternative.
  • The Retrofit code is read-only here; the TryIt blocks are stand-ins for the API layer and the interceptor chain.

Next: JSON with kotlinx.serialization and Moshi