chatgptとcopilotを使ってサンプルコードを抽出してもらい、実装しました。
依存関係の追加
build.gradle.ktsに次を追加します。
dependencies {
implementation("io.ktor:ktor-client-core:2.3.11")
implementation("io.ktor:ktor-client-cio:2.3.11")
implementation("io.ktor:ktor-client-json:2.0.0")
implementation("io.ktor:ktor-client-serialization:2.0.0")
}
ソース
httpクライアントを作ります。
リクエスト先は「https://ktor.io/」です。
class Greeting() {
private val client = HttpClient()
suspend fun greeting(): String{
val response: HttpResponse = client.get("https://ktor.io/")
return response.bodyAsText()
}
}
CoroutineScopeを使って非同期で呼び出します。
この場合、用意したResultコンポ―ザブルを使って表示しています。
val scope= rememberCoroutineScope()
var text by remember { mutableStateOf("Loading") }
LaunchedEffect(true){
scope.launch{
text = try{
Greeting().greeting()
} catch (e: Exception){
e.localizedMessage ?: "error"
}
}
}
Result(
name = text,
modifier = Modifier.padding(innerPadding)
)
結果
レスポンスを表示します。