這裏只用到基本的 CIO Engine 來取得文字資料,並開啟簡單的 logging 功能,讓初次使用的人能有個簡單的認識。

權限與依賴

AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />

libs.versions.toml

[versions]
...

kotlinx-serialization = "1.7.3"
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" }

[bundles]
ktor = [
    "ktor-client-core",
    "ktor-client-cio",
    "ktor-client-logging",
]

build.gradle.kts (module level :app)

...

dependencies {

    ...

    implementation(libs.bundles.ktor)

}

主要程式碼

KtorClient.kt

class KtorClient {
    private val client = HttpClient(CIO) {
        defaultRequest{ url("https://apidemo.kirin.app/api/v1/") }

        install(Logging) {
            logger = Logger.SIMPLE
        }
    }

    suspend fun getVersion(): String {
        return client.get("version").body()
    }
}

MainActivity.kt

class MainActivity : ComponentActivity() {

    private val ktorClient = KtorClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            var version by remember {
                mutableStateOf("")
            }

            LaunchedEffect(key1 = Unit) {
                version = ktorClient.getVersion()
            }
            KtorKata20250624Theme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Column(
                        modifier = Modifier
                            .padding(innerPadding)
                    ) {
                        Text(
                            text = version,
                            fontSize = 20.sp,
                        )
                    }
                }
            }
        }
    }
}

如果無法使用 by remember,請加上

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

參考資料

Setup Ktor for your Android app!

Practical API mapping Android example

Last modified: 2025 年 6 月 25 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.