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:
In this example, we use the CIO engine. You can also omit an engine:
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:
Engine configuration
You can configure an engine using the engine
function:
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:
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:
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:
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: