Ktor 3.0.2 Help

Creating and configuring a client

After adding the client dependencies, you can instantiate the client by creating the HttpClient class instance and passing an engine as a parameter:

import io.ktor.client.* import io.ktor.client.engine.cio.* val client = HttpClient(CIO)

In this example, we use the CIO engine. You can also omit an engine:

import io.ktor.client.* val client = HttpClient()

In this case, the client will choose an engine automatically depending on the artifacts added in a build script. You can learn how the client chooses an engine from the Default engine documentation section.

Configure the client

Basic configuration

To configure the client, you can pass an additional functional parameter to the client constructor. The HttpClientConfig class is a base class for configuring the client. For instance, you can enable response validation using the expectSuccess property:

import io.ktor.client.* import io.ktor.client.engine.cio.* val client = HttpClient(CIO) { expectSuccess = true }

Engine configuration

You can configure an engine using the engine function:

import io.ktor.client.* import io.ktor.client.engine.cio.* val client = HttpClient(CIO) { engine { // Configure an engine } }

See the Engines section for additional details.

Plugins

To install a plugin, you need to pass it to the install function inside a client configuration block. For example, you can log HTTP calls by installing the Logging plugin:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.logging.* val client = HttpClient(CIO) { install(Logging) }

You can also configure a plugin inside the install block. For example, for the Logging plugin, you can specify the logger, logging level, and condition for filtering log messages:

val client = HttpClient(CIO) { install(Logging) { logger = Logger.DEFAULT level = LogLevel.HEADERS filter { request -> request.url.host.contains("ktor.io") } sanitizeHeader { header -> header == HttpHeaders.Authorization } } }

Note that a specific plugin might require a separate dependency.

Use the client

After you've added all the required dependencies and created the client, you can use it to make requests and receive responses.

Close the client

After you finish working with the HTTP client, you need to free up the resources: threads, connections, and CoroutineScope for coroutines. To do this, call the HttpClient.close function:

client.close()

Note that the close function prohibits creating new requests but doesn't terminate currently active ones. Resources will only be released after all client requests are completed.

If you need to use HttpClient for a single request, call the use function, which automatically calls close after executing the code block:

val status = HttpClient().use { client -> // ... }
Last modified: 12 August 2024