Ktor 1.6.8 Help

Multiplatform

The Ktor HTTP client can be used in multiplatform projects and supports the following platforms:

Add dependencies

To use the Ktor HTTP client in your project, you need to add at least two dependencies: a client dependency and an engine dependency. For a multiplatform project, you need to add these dependencies as follows:

  1. To use the Ktor client in common code, add the dependency to ktor-client-core to the commonMain source set in the build.gradle or build.gradle.kts file:

    commonMain { dependencies { implementation "io.ktor:ktor-client-core:$ktor_version" } }
    val commonMain by getting { dependencies { implementation("io.ktor:ktor-client-core:$ktor_version") } }

  2. Add an engine dependency for the required platform to the corresponding source set. For Android, you can add the Android engine dependency to the androidMain source set:

    androidMain { dependencies { implementation "io.ktor:ktor-client-android:$ktor_version" } }
    val androidMain by getting { dependencies { implementation("io.ktor:ktor-client-android:$ktor_version") } }

    For iOS, you need to add the iOS engine dependency to iosMain:

    iosMain { dependencies { implementation "io.ktor:ktor-client-ios:$ktor_version" } }
    val iosMain by getting { dependencies { implementation("io.ktor:ktor-client-ios:$ktor_version") } }

    To learn which engines are supported for each platform, see Add an engine dependency.

Create the client

To create the client in a multiplatform project, call the HttpClient constructor in a project's common code:

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

In this code snippet, the HttpClient constructor doesn't accept an engine as a parameter: the client will choose an engine for the required platform depending on the artifacts added in a build script.

If you need to adjust an engine configuration for specific platforms, pass a corresponding engine class as an argument to the HttpClient constructor and configure an engine using the engine method, for example:

import io.ktor.client.* import io.ktor.client.engine.android.* import java.net.Proxy import java.net.InetSocketAddress val client = HttpClient(Android) { engine { // this: [[[AndroidEngineConfig|https://api.ktor.io/ktor-client/ktor-client-android/ktor-client-android/io.ktor.client.engine.android/-android-engine-config/index.html]]] connectTimeout = 100_000 socketTimeout = 100_000 proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress("localhost", 8080)) } }

You can learn how to configure all engine types from Engines.

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. Learn more from Make a request.

Code example

The mpp/client-mpp project shows how to use a Ktor client in a multiplatform application. This application works on the following platforms: Android, iOS, JavaScript, and macosX64.

Last modified: 28 May 2021