Kotlin HTTP客户端:正确发起请求
现代Android开发和Kotlin后端服务很少能不涉及与远程API的交互。创建一个可靠的HTTP客户端是一项基本任务,其正确实现关系到整个应用的稳定性。在本文中,我们将分析如何使用两个最流行的库:Ktor Client 和 OkHttp 在Kotlin中发起HTTP请求。您将学习如何发送GET和POST请求、处理JSON、管理错误以及编写干净、可维护的代码。
为什么Ktor Client是现代Kotlin开发者的选择
Ktor Client是一个异步HTTP客户端,由JetBrains团队专门为Kotlin创建。它完全支持协程(coroutines),使代码简洁且安全。与OkHttp不同,Ktor从一开始就设计为支持多平台:同一套代码可以在Android、iOS、JVM、JS和Native上运行。
安装依赖
要使用Ktor Client,请在build.gradle.kts文件中添加以下依赖:
dependencies { // 基础客户端 implementation("io.ktor:ktor-client-core:2.3.7") // JVM引擎(OkHttp或CIO) implementation("io.ktor:ktor-client-okhttp:2.3.7") // 用于JSON序列化 implementation("io.ktor:ktor-client-content-negotiation:2.3.7") implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7") // Kotlinx Serialization implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")}简单的GET请求
创建一个HTTP客户端并向测试API(JSONPlaceholder)发起GET请求:
import io.ktor.client.*import io.ktor.client.request.*import io.ktor.client.statement.*import kotlinx.coroutines.runBlocking
suspend fun fetchUser(userId: Int): String { val client = HttpClient { // 基础配置 engine { // OkHttp引擎设置 } } val response: HttpResponse = client.get("https://jsonplaceholder.typicode.com/users/$userId") return response.bodyAsText()}
fun main() = runBlocking { val userData = fetchUser(1) println(userData)}请注意:fetchUser是一个suspend函数。这使得它可以在不阻塞线程的情况下从协程中调用。
带JSON体的POST请求
要发送JSON格式的数据,请接入ContentNegotiation插件并定义一个data类:
import io.ktor.client.*import io.ktor.client.call.*import io.ktor.client.plugins.contentnegotiation.*import io.ktor.client.request.*import io.ktor.http.*import io.ktor.serialization.kotlinx.json.*import kotlinx.serialization.Serializableimport kotlinx.serialization.json.Json
@Serializabledata class Post(val userId: Int, val id: Int? = null, val title: String, val body: String)
suspend fun createPost(post: Post): Post { val client = HttpClient { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true prettyPrint = true }) } } val response: Post = client.post("https://jsonplaceholder.typicode.com/posts") { contentType(ContentType.Application.Json) setBody(post) }.body() client.close() return response}
fun main() = runBlocking { val newPost = Post(userId = 1, title = "Ktor Client", body = "运行完美!") val createdPost = createPost(newPost) println(createdPost)}关键点:ContentNegotiation插件会自动将对象序列化为JSON,并将响应反序列化回data类。
OkHttp — Android的成熟标准
OkHttp仍然是Android开发中网络请求的事实标准。它快速、可靠,并支持