In addition to HTTP serving, Ktor also includes a flexible asynchronous HTTP client. This client supports several configurable engines, and has its own set of features.
The main functionality is available through the io.ktor:ktor-client-core:$ktor_version
artifact.
And each engine, is provided in separate artifacts.
Table of contents:
You can check how to make requests, and how to receive responses in their respective sections.
Remember that requests are asynchronous, but when performing requests, the API suspends further requests
and your function will be suspended until done. If you want to perform several requests at once
in the same block, you can use launch
or async
functions and later get the results.
For example:
suspend fun sequentialRequests() {
val client = HttpClient(Apache)
// Get the content of an URL.
val bytes1 = client.call("https://127.0.0.1:8080/a").response.readBytes() // Suspension point.
// Once the previous request is done, get the content of an URL.
val bytes2 = client.call("https://127.0.0.1:8080/b").response.readBytes() // Suspension point.
client.close()
}
suspend fun parallelRequests() {
val client1 = HttpClient(Apache)
val client2 = HttpClient(Apache)
// Start two requests asynchronously.
val req1 = async { client1.call("https://127.0.0.1:8080/a").response.readBytes() }
val req2 = async { client2.call("https://127.0.0.1:8080/b").response.readBytes() }
// Get the request contents without blocking threads, but suspending the function until both
// requests are done.
val bytes1 = req1.await() // Suspension point.
val bytes2 = req2.await() // Suspension point.
client2.close()
client1.close()
}
For more information, check the examples page with some examples.
For more information, check the features page with all the available features.