Configuring the client

    For example you can add CIO engine dependency in build.gradle like this:

    Next you can create client as here:

    1. 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:

    1. 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:

    1. // Close and wait for 3 seconds.
    2. withTimeout(3000) {
    3. client.close()
    4. }
    5. } catch (timeout: TimeoutCancellationException) {
    6. client.cancel()
    7. }

    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:

    1. val client = HttpClient(CIO) {
    2. engine {
    3. // engine configuration

    See Engines section for additional details.