HTTP-Client in Kotlin: Anfragen richtig stellen: von A bis Z
Moderne Entwicklung mit Kotlin ist ohne Netzwerkkommunikation undenkbar. Ob Android-App, Serverlösung mit Ktor oder Desktop-Anwendung – HTTP-Anfragen bleiben die wichtigste Methode zum Datenaustausch. In diesem Artikel analysieren wir, wie man einen HTTP-Client in Kotlin richtig organisiert, betrachten beliebte Bibliotheken und Best Practices.
Warum ist Kotlin ideal für HTTP-Anfragen?
Kotlin bietet moderne Syntax, Null-Sicherheit und vollständige Kompatibilität mit dem Java-Ökosystem. Dank Coroutinen und Streaming-APIs wird die Netzwerkarbeit sauber und asynchron. Die Hauptvorteile:
- Coroutinen – leichtgewichtige Threads für asynchrone Operationen ohne Blockaden
- Type-safe Builder – bequeme Konstruktion von HTTP-Anfragen
- Sealed Classes – elegante Verarbeitung von Antwortzuständen
- Extension Functions – Erweiterung der Funktionalität von Bibliotheken
Auswahl des HTTP-Clients für Kotlin
Heutzutage dominieren drei Bibliotheken das Kotlin-Ökosystem: OkHttp, Ktor Client und Retrofit. Betrachten wir jede mit Codebeispielen.
1. OkHttp – die bewährte Wahl
OkHttp von Square ist der beliebteste HTTP-Client für die JVM. Er ist effizient, unterstützt HTTP/2, automatische Komprimierung und Caching.
// build.gradle.ktsimplementation("com.squareup.okhttp3:okhttp:4.12.0")
// Beispiel einer GET-Anfrage mit OkHttpimport okhttp3.OkHttpClientimport okhttp3.Requestimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext
class OkHttpExample { private val client = OkHttpClient.Builder() .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS) .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS) .build()
suspend fun fetchData(url: String): String = withContext(Dispatchers.IO) { val request = Request.Builder() .url(url) .header("Accept", "application/json") .build()
client.newCall(request).execute().use { response -> if (!response.isSuccessful) { throw RuntimeException("Fehler: ${response.code}") } response.body?.string() ?: throw RuntimeException("Leere Antwort") } }}2. Ktor Client – die native Wahl für Kotlin
Ktor Client ist Teil des JetBrains-Ökosystems, vollständig in Kotlin geschrieben und unterstützt Multiplattform. Ideal für Ktor-Server und Android/iOS-Projekte.
// build.gradle.ktsimplementation("io.ktor:ktor-client-core:2.3.7")implementation("io.ktor:ktor-client-cio:2.3.7")implementation("io.ktor:ktor-client-content-negotiation:2.3.7")implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")
import io.ktor.client.*import io.ktor.client.call.*import io.ktor.client.engine.cio.*import io.ktor.client.plugins.contentnegotiation.*import io.ktor.client.request.*import io.ktor.client.statement.*import io.ktor.serialization.kotlinx.json.*import kotlinx.serialization.Serializable
@Serializabledata class Post(val userId: Int, val id: Int, val title: String, val body: String)
class KtorExample { private val client = HttpClient(CIO) { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true isLenient = true }) } engine { requestTimeout = 30_000 } }
suspend fun getPost(id: Int): Post { val response: HttpResponse = client.get("https://jsonplaceholder.typicode.com/posts/$id") return response.body() }
suspend fun createPost(post: Post): Post { val response: HttpResponse = client.post("https://jsonplaceholder.typicode.com/posts") { setBody(post)