Configuring the client
For example you can add CIO
engine dependency in build.gradle
like this:
Next you can create client as here:
val client = HttpClient(CIO)
where CIO
is engine class here. If you confused which engine class you should use consider using .
If you’re using multiplatform, you can omit the engine:
It’s safe to create multiple instance of client or use the same client for multiple requests.
Ktor client is holding resources: prepared threads, coroutines and connections. After you finish working with the client, you may wish to release it by calling close
:
client.close()
If you want to use a client to make only one request consider use
-ing it. The client will be automatically closed once the passed block has been executed:
The method close
signals to stop executing new requests. It wouldn’t block and allows all current requests to finish successfully and release resources. You can also wait for closing with the join
method or halt any activity using the cancel
method. For example:
// Close and wait for 3 seconds.
withTimeout(3000) {
client.close()
}
} catch (timeout: TimeoutCancellationException) {
client.cancel()
}
To configure the client you can pass additional functional parameter to client constructor. The client configured with HttpClientEngineConfig.
For example you can limit threadCount
or setup :
You also can configure engine using the engine
method in block:
val client = HttpClient(CIO) {
engine {
// engine configuration
See Engines section for additional details.