Ktor Client 是 Kotlin 中由 JetBrains 开发的一个异步 HTTP 客户端,用于构建网络请求。它具有灵活的 API,能够轻松处理 HTTP 通信,并且可以在多种平台上运行,包括 Android、JVM、iOS、和 JavaScript。Ktor Client 可以处理各种请求方法(如 GET、POST、PUT、DELETE 等),并支持协程,使得异步网络请求非常简单和高效。
1. Ktor Client 的依赖配置
要在项目中使用 Ktor Client,首先需要在项目的 build.gradle.kts
中添加依赖。
Gradle 配置(Kotlin DSL 示例):
dependencies {
implementation("io.ktor:ktor-client-core:2.0.0") // 核心模块
implementation("io.ktor:ktor-client-cio:2.0.0") // CIO 引擎,或其他引擎
implementation("io.ktor:ktor-client-json:2.0.0") // JSON 支持
implementation("io.ktor:ktor-client-logging:2.0.0") // 日志支持
implementation("io.ktor:ktor-client-serialization:2.0.0") // 序列化
}
2. 选择引擎
Ktor Client 支持多种引擎,如:
- CIO:轻量的多平台异步 I/O 引擎。
- Apache:使用 Apache HTTP Client 作为引擎。
- OkHttp:使用 OkHttp 作为引擎(通常用于 Android 项目)。
在项目中使用不同的引擎时,只需要替换对应的依赖。例如,使用 OkHttp
引擎:
implementation("io.ktor:ktor-client-okhttp:2.0.0")
3. 基本使用示例
初始化 Ktor 客户端:
import io.ktor.client.*
import io.ktor.client.engine.cio.* // 使用 CIO 引擎
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.logging.*
val client = HttpClient(CIO) {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
install(Logging) {
level = LogLevel.INFO
}
}
发送 GET 请求:
import io.ktor.client.request.*
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val response: String = client.get("https://jsonplaceholder.typicode.com/posts/1")
println(response)
}
发送 POST 请求:
import io.ktor.client.request.*
import io.ktor.http.*
suspend fun sendPostRequest() {
val response: String = client.post("https://jsonplaceholder.typicode.com/posts") {
contentType(ContentType.Application.Json)
body = """
{
"title": "foo",
"body": "bar",
"userId": 1
}
"""
}
println(response)
}
4. 响应处理
Ktor Client 提供多种方式来处理服务器响应,可以直接解析 JSON 响应、处理错误状态码、以及自定义解析。
使用 HttpResponse
:
import io.ktor.client.statement.*
suspend fun fetchResponse() {
val response: HttpResponse = client.get("https://jsonplaceholder.typicode.com/posts/1")
println(response.status) // 获取状态码
println(response.readText()) // 读取响应内容
}
5. 异常处理
Ktor Client 支持协程,因此可以结合 try-catch
来处理网络请求中的错误。
import io.ktor.client.features.*
import io.ktor.client.features.logging.*
import io.ktor.network.sockets.*
import kotlinx.coroutines.*
suspend fun safeRequest() {
try {
val response: String = client.get("https://invalid-url.com")
println(response)
} catch (e: RedirectResponseException) {
// 3XX 错误
println("Redirect: ${e.response.status}")
} catch (e: ClientRequestException) {
// 4XX 错误
println("Client error: ${e.response.status}")
} catch (e: ServerResponseException) {
// 5XX 错误
println("Server error: ${e.response.status}")
} catch (e: Exception) {
// 其他错误
println("Error: ${e.message}")
}
}
6. 关闭客户端
使用完 Ktor 客户端后,需要显式关闭客户端资源。
client.close()
7. Ktor Client 的其他功能
- WebSocket:支持 WebSocket 通信。
- 认证:支持 Basic Auth 和 Bearer Token 等认证机制。
- Cookies:支持处理 HTTP Cookies。
- Retry:支持失败请求的重试机制。