Kotlin

Ktor Client — GET Request

admin by @admin ADMIN
5h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Ktor is JetBrains' Kotlin-first HTTP client. Multiplatform (JVM, JS, Native). Coroutine-native — every call is a suspend function.
Kotlin
Raw
// build.gradle.kts:
//   implementation("io.ktor:ktor-client-core:2.3.+")
//   implementation("io.ktor:ktor-client-cio:2.3.+")    // CIO engine, JVM
//   implementation("io.ktor:ktor-client-content-negotiation:2.3.+")
//   implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.+")

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.runBlocking

val client = HttpClient(CIO) {
    expectSuccess = true                       // throw on 4xx/5xx
}

suspend fun fetchPage(url: String): String {
    val response: HttpResponse = client.get(url) {
        headers {
            append("User-Agent", "myapp/1.0")
            append("Accept",     "application/json")
        }
    }
    return response.bodyAsText()
}

fun main() = runBlocking {
    val body = fetchPage("https://api.github.com")
    println(body.take(200))
    client.close()
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.