HTTPによる配信機能に加え、Ktorは非同期で柔軟なHTTPクライアント機能も含んでいます。 このクライアント機能はいくつかの設定可能なengineをサポートしています。 またいくつかのFeatureもサポートしています。
メイン機能はio.ktor:ktor-client-core:$ktor_version
アーティファクトを通じて利用可能です。
各engineは、アーティファクトとして分離された上で提供されています。
目次:
リクエストの作り方を確認してください。 また、レスポンスの受け取り方も確認してください。
リクエストは非同期ですが、リクエスト実行時にAPIは別の追加のリクエストを行わず、実行終了するまで関数は停止することを覚えておいてください。
いくつかのリクエストを同じブロック内で一度に実行したい場合は、launch
かasync
関数を使い結果を遅延で受け取れば良いです。
例えば:
suspend fun sequentialRequests() {
val client = HttpClient()
// Get the content of an URL.
val firstBytes = client.get<ByteArray>("https://127.0.0.1:8080/a")
// Once the previous request is done, get the content of an URL.
val secondBytes = client.get<ByteArray>("https://127.0.0.1:8080/b")
client.close()
}
suspend fun parallelRequests() = coroutineScope<Unit> {
val client = HttpClient()
// Start two requests asynchronously.
val firstRequest = async { client.get<ByteArray>("https://127.0.0.1:8080/a") }
val secondRequest = async { client.get<ByteArray>("https://127.0.0.1:8080/b") }
// Get the request contents without blocking threads, but suspending the function until both
// requests are done.
val bytes1 = firstRequest.await() // Suspension point.
val bytes2 = secondRequest.await() // Suspension point.
client.close()
}
サンプルページにいくつかの例があります。
Featureページに利用可能なすべての機能があります。