探索 Ktor:用于 Kotlin 的现代网络框架
Source: Dev.to
Ktor 是由 JetBrains 开发的异步网络框架,旨在使用 Kotlin 构建服务器和客户端应用程序。虽然 Retrofit 长期以来一直是 Android 网络请求的首选标准,但许多开发者认为 Ktor 是 Kotlin‑优先网络的未来。
在 Ktor 与 Retrofit 之间的选择最终取决于项目需求、范围以及开发者的偏好。下面是一份在 Android 项目中设置和使用 Ktor 的实用指南。
项目设置和依赖
添加 Ktor 和序列化插件
在根目录的 build.gradle.kts 文件中,应用 Kotlin 序列化插件:
plugins {
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.20"
}
添加 Ktor 依赖
在应用层级的 build.gradle.kts 中,加入所需的 Ktor 库:
plugins {
id("kotlinx-serialization")
}
dependencies {
implementation(platform("io.ktor:ktor-bom:3.1.2"))
implementation("io.ktor:ktor-client-android")
implementation("io.ktor:ktor-client-serialization")
implementation("io.ktor:ktor-client-logging")
implementation("io.ktor:ktor-client-content-negotiation")
implementation("io.ktor:ktor-serialization-kotlinx-json")
}
创建可重用的 HttpClient
可重用客户端的好处
- 持久连接 – 保持连接存活,降低后续请求的延迟。
- Kotlin 多平台兼容性 – 在 Android、iOS 以及其他目标之间共享网络逻辑。
- 资源管理 – 简化清理(例如
client.close()),防止泄漏。
创建客户端实例的示例
private const val NETWORK_TIME_OUT = 15_000
val httpClient = HttpClient(Android) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
install(HttpTimeout) {
requestTimeoutMillis = NETWORK_TIME_OUT
connectTimeoutMillis = NETWORK_TIME_OUT
socketTimeoutMillis = NETWORK_TIME_OUT
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.v("KtorLogger", message)
}
}
level = LogLevel.ALL
}
install(DefaultRequest) {
header(HttpHeaders.ContentType, ContentType.Application.Json)
}
defaultRequest {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
}
}
使用 Ktor 发起请求
示例:GET 请求
suspend fun fetchLocationsList(): User = httpClient.get("https://api.example.com/locations/123").body()
示例:POST 请求
suspend fun createLocationList(location: Location): HttpResponse = httpClient.post("https://api.example.com/locations") {
contentType(ContentType.Application.Json)
setBody(location)
}
创建数据模型
@Serializable
data class Location(
val locationId: Int,
val locationName: String,
val locationLatLong: String
)
注意: 序列化插件已在 app‑level
build.gradle.kts中添加。
日志记录与调试
Ktor 内置的日志功能让您能够在 Logcat 中监控请求和响应。它可以平滑地与 Koin 或 Hilt 等依赖注入框架集成,并且您可以将其与 Timber 或 Klogging 等日志库配合使用,以获得更丰富的输出。
最后思考
Retrofit 仍然是传统 Android 应用的可靠、稳固选择,而 Ktor 在现代、Kotlin 优先和多平台环境中表现出色。上述步骤应能帮助您快速入门 Ktor。未来的文章将探讨与依赖注入(Koin)更深层的集成以及使用 Timber 的高级日志记录。
尝试一下 Ktor,体验 Kotlin 优先开发的灵活性。