HTTP client

suggest change

Kotlin applications consume REST APIs and external HTTP services using modern HTTP client libraries. The two most prominent choices are Ktor Client—JetBrains' multiplatform asynchronous HTTP client powered by Kotlin coroutines—and OkHttp, alongside the built-in Java 11+ java.net.http.HttpClient.


Ktor Client

Ktor Client is non-blocking, multiplatform (JVM, Android, iOS, JS, Native), and integrates directly with Kotlin Coroutines and kotlinx.serialization.

Dependencies (Gradle)

val ktorVersion = "3.6.0"
dependencies {
    implementation("io.ktor:ktor-client-core:$ktorVersion")
    implementation("io.ktor:ktor-client-cio:$ktorVersion")             // Coroutine I/O engine
    implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
    implementation("io.ktor:ktor-client-logging:$ktorVersion")
}

Configuring the Client with Plugins

import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class Post(val id: Int? = null, val title: String, val body: String, val userId: Int)

fun createHttpClient(): HttpClient {
    return HttpClient(CIO) {
        // Automatic JSON serialization/deserialization
        install(ContentNegotiation) {
            json(Json {
                prettyPrint = true
                isLenient = true
                ignoreUnknownKeys = true
            })
        }

        // Logging HTTP traffic
        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.INFO
        }

        // Global timeouts
        install(HttpTimeout) {
            requestTimeoutMillis = 15000
            connectTimeoutMillis = 10000
            socketTimeoutMillis = 15000
        }

        // Throw ClientRequestException / ServerResponseException for 4xx / 5xx responses
        expectSuccess = true

        // Default request base URL and headers
        defaultRequest {
            url("https://jsonplaceholder.typicode.com/")
            contentType(ContentType.Application.Json)
            accept(ContentType.Application.Json)
        }
    }
}

Executing Requests

suspend fun main() {
    val client = createHttpClient()

    try {
        // 1. GET request with typed deserialization
        val post: Post = client.get("posts/1").body()
        println("Fetched Post: ${post.title}")

        // 2. GET request with query parameters
        val userPosts: List<Post> = client.get("posts") {
            parameter("userId", 1)
        }.body()
        println("Found ${userPosts.size} posts for user 1.")

        // 3. POST request with JSON payload
        val newPost = Post(title = "Learning Kotlin", body = "HTTP client in Kotlin is great!", userId = 1)
        val createdPost: Post = client.post("posts") {
            setBody(newPost)
        }.body()
        println("Created post with ID: ${createdPost.id}")

    } catch (e: ClientRequestException) {
        // Handles 4xx response codes
        println("Client error: ${e.response.status}")
    } catch (e: ServerResponseException) {
        // Handles 5xx response codes
        println("Server error: ${e.response.status}")
    } finally {
        client.close()
    }
}

Built-in java.net.http.HttpClient (Java 11+)

For lightweight projects without extra dependencies, standard Java HttpClient works seamlessly with Kotlin:

import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration

fun standardJavaClientExample() {
    val client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build()

    // 1. Synchronous GET
    val getRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://httpbin.org/get?query=kotlin"))
        .timeout(Duration.ofSeconds(5))
        .header("User-Agent", "Kotlin-JavaHttpClient/1.0")
        .GET()
        .build()

    val getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString())
    println("Status: ${getResponse.statusCode()}")
    println("Body: ${getResponse.body().take(100)}...")

    // 2. POST with String Body
    val postPayload = """{"message": "Hello from standard client"}"""
    val postRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://httpbin.org/post"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(postPayload))
        .build()

    val postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString())
    println("Post Response: ${postResponse.statusCode()}")
}

Using Java 11 HttpClient Asynchronously with Coroutines

Standard CompletableFuture responses can be awaited natively inside coroutines using kotlinx.coroutines.future.await():

import kotlinx.coroutines.future.await
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

suspend fun asyncFetch(client: HttpClient, url: String): String {
    val request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .GET()
        .build()

    val response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).await()
    return response.body()
}

OkHttp

OkHttp provides connection pooling, transparent GZIP decompression, and interceptors:

import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit

fun okHttpClientExample() {
    val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()

    val jsonMediaType = "application/json; charset=utf-8".toMediaType()
    val requestBody = """{"title": "OkHttp with Kotlin"}""".toRequestBody(jsonMediaType)

    val request = Request.Builder()
        .url("https://httpbin.org/post")
        .post(requestBody)
        .build()

    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) {
            error("Unexpected code: ${response.code}")
        }
        println("Response: ${response.body.string()}")
    }
}

Best Practices

  1. Reuse Client Instances: HttpClient (both Ktor and OkHttp) maintains connection pools, dispatchers, and SSL sessions. Create a single instance per application and reuse it across requests.
  2. Always Configure Timeouts: Never rely on infinite default timeouts; configure connect, request, and socket timeouts explicitly.
  3. Always Close or Consume Response Bodies: In OkHttp and Java HttpResponse.BodyHandlers.ofInputStream(), failing to close response streams leaks socket connections.
  4. Use Structured Concurrency with Ktor: When launching multiple parallel HTTP requests, use coroutineScope and async:
    coroutineScope {
        val profileDeferred = async { client.get("/user/1").body<Profile>() }
        val ordersDeferred = async { client.get("/user/1/orders").body<List<Order>>() }
        val profile = profileDeferred.await()
        val orders = ordersDeferred.await()
    }
    

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents