Client

note

Client - 图1

This help topic is in development and will be updated in the future.

Adding an engine dependency

The first thing you need to do before using the client is to add a client engine dependency. Client engine is a request executor that performs requests from ktor API. There are many client engines for each platform available out of the box: Apache, OkHttp, Android, Ios, Js, Jetty, CIO and Mock. You can read more in the Multiplatform section.

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

  1. dependencies {
  2. implementation("io.ktor:ktor-client-cio:$ktor_version")
  3. }

Creating client

Next you can create a 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 CIO.

If you’re using multiplatform, you can omit the engine:

  1. val client = HttpClient()

Ktor will choose an engine among the ones that are available from the included artifacts using a ServiceLoader on the JVM, or similar approach in the other platforms. If there are multiple engines in the dependencies Ktor chooses first in alphabetical order of engine name.

It’s safe to create multiple instance of client or use the same client for multiple requests.

Releasing resources

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:

  1. val status = HttpClient().use { client ->
  2. ...
  3. }

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. try {
  2. // Close and wait for 3 seconds.
  3. withTimeout(3000) {
  4. client.close()
  5. client.join()
  6. }
  7. } catch (timeout: TimeoutCancellationException) {
  8. // Cancel after timeout
  9. client.cancel()
  10. }

Ktor HttpClient follows CoroutineScope lifecycle. Check out Coroutines guide to learn more.

Client configuration

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 proxy:

  1. val client = HttpClient(CIO) {
  2. threadCount = 2
  3. }

You also can configure an engine using the engine method in a block:

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

See Engines section for additional details.

Proceed to Preparing the request.