0
0

KtorでGETリクエストを行う方法

Posted at

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)
    )

結果

レスポンスを表示します。

スクリーンショット 2024-08-27 181607.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0