Ktor HTTP client core library - asynchronous framework for creating HTTP clients in Kotlin multiplatform
—
Core functionality for creating and configuring HTTP clients with engine selection, plugin installation, and platform-specific configuration options.
Create HTTP client instances with different configuration options.
/**
* Creates an asynchronous HttpClient with the specified block configuration.
* Note that the client requires an engine for processing network requests.
* The HttpClientEngine is selected from the dependencies.
*/
expect fun HttpClient(
block: HttpClientConfig<*>.() -> Unit = {}
): HttpClient
/**
* Creates an asynchronous HttpClient with the specified HttpClientEngineFactory and optional block configuration.
* Note that a specific platform may require a specific engine for processing requests.
*/
fun <T : HttpClientEngineConfig> HttpClient(
engineFactory: HttpClientEngineFactory<T>,
block: HttpClientConfig<T>.() -> Unit = {}
): HttpClient
/**
* Creates an asynchronous HttpClient with the specified HttpClientEngine and optional block configuration.
*/
fun HttpClient(
engine: HttpClientEngine,
block: HttpClientConfig<*>.() -> Unit
): HttpClientUsage Examples:
import io.ktor.client.*
import io.ktor.client.engine.cio.*
// Platform-default engine (expect function)
val client1 = HttpClient {
// Configuration block
}
// Specific engine factory
val client2 = HttpClient(CIO) {
// Engine-specific configuration
}
// Pre-configured engine instance
val engine = CIO.create()
val client3 = HttpClient(engine) {
// Client configuration
}Main HTTP client class implementing CoroutineScope and Closeable for structured concurrency.
/**
* A multiplatform asynchronous HTTP client, which allows you to make requests and handle responses,
* extend its functionality with plugins, such as authentication, JSON serialization, and so on.
*/
class HttpClient(
val engine: HttpClientEngine,
private val userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()
) : CoroutineScope, Closeable {
/** A pipeline used for processing all requests sent by this client. */
val requestPipeline: HttpRequestPipeline
/** A pipeline used for processing all responses sent by the server. */
val responsePipeline: HttpResponsePipeline
/** A pipeline used for sending a request. */
val sendPipeline: HttpSendPipeline
/** A pipeline used for receiving a request. */
val receivePipeline: HttpReceivePipeline
/** Typed attributes used as a lightweight container for this client. */
val attributes: Attributes
/** Provides access to the client's engine configuration. */
val engineConfig: HttpClientEngineConfig
/** Provides access to the events of the client's lifecycle. */
val monitor: Events
override val coroutineContext: CoroutineContext
/**
* Checks if the specified capability is supported by this client.
*/
fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
/**
* Returns a new HttpClient by copying this client's configuration
* and additionally configured by the block parameter.
*/
fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
/**
* Closes the underlying engine.
*/
override fun close()
}Configuration builder for HTTP client settings and plugin installation.
/**
* HttpClient configuration builder
*/
class HttpClientConfig<T : HttpClientEngineConfig> {
/** Enable/disable redirect following */
var followRedirects: Boolean = true
/** Use default content transformers */
var useDefaultTransformers: Boolean = true
/** Fail on non-success status codes */
var expectSuccess: Boolean = false
/** Enable development mode features */
var developmentMode: Boolean
/**
* Configure engine-specific parameters
*/
fun engine(block: T.() -> Unit)
/**
* Install a plugin with configuration
*/
fun <TBuilder : Any, TPlugin : Any> install(
plugin: HttpClientPlugin<TBuilder, TPlugin>,
configure: TBuilder.() -> Unit = {}
)
/**
* Install a custom interceptor with string key
*/
fun install(key: String, block: HttpClient.() -> Unit)
/**
* Clone this configuration
*/
fun clone(): HttpClientConfig<T>
/**
* Merge another configuration into this one
*/
operator fun plusAssign(other: HttpClientConfig<out T>)
}Usage Examples:
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
val client = HttpClient(CIO) {
// Basic configuration
followRedirects = true
expectSuccess = false
// Engine configuration
engine {
maxConnectionsCount = 1000
requestTimeout = 30_000
}
// Install plugins
install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.INFO
}
install(ContentNegotiation) {
json()
}
// Custom interceptor
install("CustomMetrics") {
// Custom logic
}
}Advanced configuration management for client reuse and customization.
/**
* Clone a configuration for reuse
*/
fun HttpClientConfig<T>.clone(): HttpClientConfig<T>
/**
* Merge configurations
*/
operator fun HttpClientConfig<T>.plusAssign(other: HttpClientConfig<out T>)
/**
* Create a new client with additional configuration
*/
fun HttpClient.config(block: HttpClientConfig<*>.() -> Unit): HttpClientUsage Examples:
// Base configuration
val baseConfig = HttpClientConfig<HttpClientEngineConfig>().apply {
followRedirects = true
install(Logging)
}
// Clone and customize
val customConfig = baseConfig.clone().apply {
expectSuccess = true
install(ContentNegotiation) { json() }
}
// Create client from existing client
val baseClient = HttpClient(CIO) {
install(Logging)
}
val customClient = baseClient.config {
install(ContentNegotiation) { json() }
expectSuccess = true
}Proper client lifecycle management with structured concurrency support.
/**
* HttpClient implements Closeable for resource management
*/
interface Closeable {
fun close()
}
/**
* HttpClient implements CoroutineScope for structured concurrency
*/
interface CoroutineScope {
val coroutineContext: CoroutineContext
}Usage Examples:
import kotlinx.coroutines.*
// Use client in coroutine scope
runBlocking {
val client = HttpClient(CIO)
try {
// Make requests
val response = client.get("https://api.example.com/data")
println(response.bodyAsText())
} finally {
// Always close the client
client.close()
}
}
// Use client with use function
HttpClient(CIO).use { client ->
runBlocking {
val response = client.get("https://api.example.com/data")
println(response.bodyAsText())
}
}
// Client inherits coroutine context from engine
val client = HttpClient(CIO)
launch(client.coroutineContext) {
// This coroutine uses the client's context
val response = client.get("https://api.example.com/data")
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-client-core-iosx64