0
0

More than 1 year has passed since last update.

Android で Ktor Client をサクッと使う

Posted at

どちらかというと自分メモ

サクッとKtorクライアント

HttpClient.kt
HttpClient(Android) {
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.HEADERS
    }
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
    install(HttpTimeout) {
        requestTimeoutMillis = 1000
        socketTimeoutMillis = 2000
        connectTimeoutMillis = 2000
    }
}
ServiceImpl.kt
// #getPost : List<Response>
return try {
            client.get(END_POINT)
            // client.post<Response> { 
            //    url(END_POINT)
            //    contentType(ContentType.Application.Json)
            //    body = request
            // }
        } catch (e: Exception) {
            println("Error: ${e.message}")
            emptyList()
            // null 
        }
~~~
MainActivity.kt
// #onCreate
val post = produceState<List<Resp>>(
    initialValue = emptyList(),
    producer = {
        value = service.getPosts()
    }
)
println(" ${post.value}")

Okhttp+Retrofitと大差ない印象。

ざっくり仕様メモ

レスポンスエラ-

エラーは例外で拾える。

RedirectResponseException for 3xx responses.
ClientRequestException for 4xx responses.
ServerResponseException for 5xx responses.

拾いどころはクライアント定義時が良さげ

val client = HttpClient(android) {
    HttpResponseValidator {
        // ...
    }
}

タイムアウト

同じく例外で拾える

HttpRequestTimeoutException, ConnectTimeoutException, or SocketTimeoutException

違いがよく分からなければこちらの記事がわかりやすい.

他、AuthenticationやらCookieやら。
公式どっキュメントがわかりやすいので以下で。

参考

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