第 9 课2026.07.25
Ktor Client 是支持 Kotlin Multiplatform 的异步 HTTP 客户端。请求与响应处理可以写在共享层,Android 和 iOS 只需要提供各自的平台网络引擎。
第 9 课:用 Ktor Client 发起共享网络请求
- 日期:2026-07-25
- 课程序号:09
- 知识点:在
commonMain中配置 Ktor Client 并获取 JSON 数据
用途
Ktor Client 是支持 Kotlin Multiplatform 的异步 HTTP 客户端。请求与响应处理可以写在共享层,Android 和 iOS 只需要提供各自的平台网络引擎。
核心概念
ktor-client-core提供共享 HTTP API。- Android 与 iOS 分别加入 Android、Darwin 引擎依赖。
client.get()是挂起函数,需要从协程或另一个suspend函数调用。- 安装
ContentNegotiation和 JSON 序列化后,可用body<T>()将响应解析为@Serializable类型。 HttpClient应被复用,并在应用不再需要时统一关闭。
示例代码
共享模块依赖示意,版本继续由项目版本目录统一管理:
kotlin
kotlin {
sourceSets {
commonMain.dependencies {
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json)
}
androidMain.dependencies {
implementation(libs.ktor.client.android)
}
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
}
}
}commonMain/HttpClientFactory.kt:
kotlin
import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
fun createHttpClient(): HttpClient {
return HttpClient {
install(ContentNegotiation) {
json()
}
}
}commonMain/UserApi.kt:
kotlin
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import kotlinx.serialization.Serializable
@Serializable
data class UserDto(
val id: Long,
val name: String,
)
class UserApi(
private val client: HttpClient,
) {
suspend fun getUser(id: Long): UserDto {
return client
.get("https://example.com/users/$id")
.body()
}
}接口地址、路径参数和响应字段都应以真实服务端协议为准。
5 分钟练习
给 UserApi 增加 suspend fun getUsers(): List<UserDto>,请求路径为 https://example.com/users。
参考答案
kotlin
suspend fun getUsers(): List<UserDto> {
return client
.get("https://example.com/users")
.body()
}返回类型决定 Ktor 将响应 JSON 反序列化成 List<UserDto>;如果真实 JSON 外面还有一层对象,数据模型也必须按真实结构调整。
与上一课的联系
上一课学习了 Kotlin Serialization;本课把它接入 Ktor,让网络响应直接转换成共享数据对象。请求本身是 suspend 函数,也复用了此前的协程知识。