Ktor Client — Kotlin 的 HTTP 客户端

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 Ktor Client?

Ktor Client 是由 JetBrains 公司为 Kotlin 编程语言开发的异步 HTTP 客户端。它是 Ktor 框架的一部分,该框架用于构建服务器端和客户端应用程序。Ktor Client 可以发送 HTTP 请求(GET、POST、PUT、DELETE 等)并处理响应,支持多种引擎(OkHttp、Apache、CIO、Android 等)。

为什么需要 Ktor Client?

Ktor Client 用于与 REST API 交互、从互联网下载数据、发送表单、处理 WebSocket,以及与云服务集成。它完全用 Kotlin 编写,确保了类型安全性和代码简洁性。由于支持协程(coroutines)和 Flow,Ktor Client 非常适合异步和响应式应用程序。

如何安装 Ktor Client?

要在 Kotlin 项目中使用 Ktor Client,请在 build.gradle.kts 文件中添加依赖项:

dependencies {    implementation("io.ktor:ktor-client-core:2.3.12")    implementation("io.ktor:ktor-client-cio:2.3.12") // CIO 引擎    implementation("io.ktor:ktor-client-content-negotiation:2.3.12") // 用于 JSON    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.12") // 序列化}

如果您使用 Maven,请在 pom.xml 中添加相应的依赖项。

主要功能

  • 多种引擎: OkHttp、Apache、CIO、Android、iOS (Darwin)、JavaScript。
  • 异步: 完全支持 Kotlin 协程(suspend 函数)。
  • 插件: Content Negotiation(JSON/XML)、Logging、Auth(Basic、Bearer、OAuth)、Cookies、WebSocket。
  • 类型安全: 通过 kotlinx.serialization 进行序列化和反序列化。
  • 流式传输: 通过 streaming 处理大文件。

Kotlin 代码示例

import io.ktor.client.*import io.ktor.client.engine.cio.*import io.ktor.client.request.*import io.ktor.client.statement.*import io.ktor.http.*import kotlinx.serialization.Serializableimport io.ktor.client.plugins.contentnegotiation.*import io.ktor.serialization.kotlinx.json.*

@Serializabledata class Post(val userId: Int, val id: Int, val title: String, val body: String)

suspend fun fetchPost(): Post { val client = HttpClient(CIO) { install(ContentNegotiation) { json() } } val response: HttpResponse = client.get("https://jsonplaceholder.typicode.com/posts/1") val post: Post = response.body() client.close() return post}

fun main() = runBlocking { val post = fetchPost() println("Title: ${post.title}")}

何时使用 Ktor Client?

建议在 Kotlin 项目(JVM、Android、Native、JS)中使用 Ktor Client,当需要轻量级、异步且现代化的 HTTP 客户端时。它在微服务、Android 应用、多平台项目(KMP)以及与 Kotlin 协程配合使用时尤其有用。如果您需要与 Kotlin 和 JetBrains 生态系统完全集成,Ktor Client 是最佳选择。

推荐