簡介
這個範例模擬以登入表單的方式,透過 post 方法,來取的 JWT 的認證 Token。
權限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
依賴
我使用的 kotlin 版本是 2.1.20
一般方式
build.gradle.kts (Module level: app)
plugins {
...
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.20"
}
dependencies {
...
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
implementation("io.ktor:ktor-client-core:3.0.2")
implementation("io.ktor:ktor-client-cio:3.0.2")
implementation("io.ktor:ktor-client-logging:3.0.2")
implementation("io.ktor:ktor-client-content-negotiation:3.0.2")
implementation("io.ktor:ktor-serialization-kotlinx-json:3.0.2")
}
Version Catalog 方式
libs.versions.toml
[versions]
...
kotlinx-serialization = "1.8.1"
ktor = "3.0.2"
[libraries]
...
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" }
ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktor" }
ktor-client-content-negotiation= { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-kotlinx-json= { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
[bundles]
ktor = [
"ktor-client-core",
"ktor-client-cio",
"ktor-client-logging",
"ktor-client-content-negotiation",
"ktor-serialization-kotlinx-json",
]
build.gradle.kts (module level :app)
...
dependencies {
...
implementation(libs.bundles.ktor)
}
主要程式碼
以 Form Data 的方式傳遞資料
LoginResponse.kt
@Serializable
data class LoginResponse(
@SerialName("access_token")
val accessToken: String? = null,
@SerialName("token_type")
val tokenType: String? = null,
@SerialName("expires_in")
val expiresIn: Long? = null,
val message: String? = null,
)
這是依據 json 的資料結構所建立的資料類別,Ktor client 可以將 json 資料,直接轉化為這個類別的實例。
KtorClient.kt
class KtorClient {
private val client = HttpClient(CIO) {
install(Logging) {
logger = Logger.SIMPLE
}
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
}
)
}
}
suspend fun login(): LoginResponse {
val result = client.submitForm(
url = "https://apidemo.kirin.app/api/v1/authorizations",
formParameters = parameters {
append("username", "test")
append("password", "123456")
},
)
return result.body()
}
}
MainActivity.kt
class MainActivity : ComponentActivity() {
private val ktorClient = KtorClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
// 主要的程式碼
LaunchedEffect(key1 = Unit) {
val loginResponse = ktorClient.login()
println(loginResponse)
}
// 這部分不變
KtorKata20250624Theme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
) {
Text(
text = version,
fontSize = 20.sp,
)
}
}
}
}
}
}
執行 app,就可以在 logcat 中,看到取得的 JWT Token 資料。
以 json 的型式傳遞資料
LoginRequest.kt
@Serializable
data class LoginRequest(
val username: String,
val password: String,
)
KtorClient.kt
class KtorClient {
private val client = HttpClient(CIO) {
install(Logging) {
logger = Logger.SIMPLE
}
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
}
)
}
}
suspend fun login(): LoginResponse {
val result = client.post {
url("https://apidemo.kirin.app/api/v1/authorizations")
contentType(ContentType.Application.Json)
setBody(LoginRequest(
username = "test",
password = "123456"
))
}
// val result = client.submitForm(
// url = "https://apidemo.kirin.app/api/v1/authorizations",
// formParameters = parameters {
// append("username", "test")
// append("password", "123456")
// },
// )
return result.body()
}
}
執行 app,就可以在 logcat 中,看到取得的 JWT Token 資料。
參考資料
Setup Ktor for your Android app!
Practical API mapping Android example
Ktor Tutorial for Android & Kotlin Mult
https://ktor.io/docs/client-serialization.html#configure_serializer
Android Login API Implementation with KTOR HTTP Client and Kotlin Coroutines
Comments