どちらかというと自分メモ
サクッと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やら。
公式どっキュメントがわかりやすいので以下で。
参考