Kotlin 网络编程
HTTP 请求
使用 HttpURLConnection
import java.net.HttpURLConnection
import java.net.URL
fun main() {
val url = URL("https://api.example.com/data")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("Accept", "application/json")
if (connection.responseCode == 200) {
val response = connection.inputStream.bufferedReader().readText()
println(response)
}
connection.disconnect()
}
使用 khttp 库
// build.gradle.kts
dependencies {
implementation("khttp:khttp:0.1.0")
}
import khttp.get
fun main() {
val response = get("https://api.example.com/users")
println(response.statusCode)
println(response.jsonObject)
}
使用 Fuel 库
// build.gradle.kts
dependencies {
implementation("com.github.kittinunf.fuel:fuel:2.3.1")
}
import com.github.kittinunf.fuel.httpGet
fun main() {
"https://api.example.com/users".httpGet().response { _, _, result ->
val (data, _) = result
println(String(data!!))
}
}
JSON 解析
使用 Gson
// build.gradle.kts
dependencies {
implementation("com.google.code.gson:gson:2.10.1")
}
import com.google.gson.Gson
data class User(val name: String, val age: Int)
fun main() {
val gson = Gson()
// JSON 转对象
val json = """{"name": "Tom", "age": 25}"""
val user = gson.fromJson(json, User::class.java)
// 对象转 JSON
val newJson = gson.toJson(User("Jerry", 30))
println(newJson)
}
使用 kotlinx.serialization
// build.gradle.kts
plugins {
kotlin("jvm") version "1.9.22"
kotlin("plugin.serialization") version "1.9.22"
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")
}
import kotlinx.serialization.*
@Serializable
data class User(val name: String, val age: Int)
fun main() {
// JSON 转对象
val user = Json.decodeFromString<User>("""{"name": "Tom", "age": 25}""")
// 对象转 JSON
val json = Json.encodeToString(User("Jerry", 30))
println(json)
}
使用协程
import kotlinx.coroutines.*
import java.net.HttpURLConnection
import java.net.URL
suspend fun fetchData(url: String): String = withContext(Dispatchers.IO) {
val connection = URL(url).openConnection() as HttpURLConnection
try {
connection.responseCode
connection.inputStream.bufferedReader().readText()
} finally {
connection.disconnect()
}
}
fun main() = runBlocking {
val data = fetchData("https://api.example.com/data")
println(data)
}