Ktor HTTP client core library providing asynchronous HTTP client capabilities for Kotlin multiplatform applications
—
Comprehensive client setup and configuration including engine selection, connection settings, timeout configuration, and client lifecycle management.
Create HTTP client instances with optional engine and configuration.
/**
* Creates an HTTP client with the specified engine and configuration
* @param engine - The HTTP client engine to use (defaults to platform-specific engine)
* @param block - Configuration block for client setup
*/
class HttpClient(
engine: HttpClientEngine = HttpClientEngineContainer.default,
block: HttpClientConfig<*>.() -> Unit = {}
) : Closeable
/**
* Creates an HTTP client with default engine and configuration
* @param block - Configuration block for client setup
*/
fun HttpClient(
block: HttpClientConfig<*>.() -> Unit = {}
): HttpClientUsage Examples:
import io.ktor.client.*
import io.ktor.client.engine.cio.*
// Default client
val client = HttpClient()
// Client with specific engine
val cioClient = HttpClient(CIO) {
engine {
maxConnectionsCount = 1000
endpoint {
maxConnectionsPerRoute = 100
}
}
}
// Client with configuration
val configuredClient = HttpClient {
expectSuccess = false
followRedirects = true
}Main configuration class for HttpClient setup.
/**
* Configuration class for HttpClient
* @param T - Type of the engine configuration
*/
class HttpClientConfig<T : HttpClientEngineConfig>(
val engine: HttpClientEngineFactory<T>
) {
/** Whether to follow HTTP redirects automatically */
var followRedirects: Boolean = true
/** Whether to validate response status codes (throws exceptions for 4xx/5xx) */
var expectSuccess: Boolean = true
/** Whether to use default content transformers */
var useDefaultTransformers: Boolean = true
/** Development mode flag for enhanced debugging */
var developmentMode: Boolean = false
/** Clone this configuration */
fun clone(): HttpClientConfig<T>
/** Merge configuration from another config */
operator fun plusAssign(other: HttpClientConfig<out T>)
}Configure the underlying HTTP engine.
/**
* Configure the HTTP client engine
* @param block - Engine configuration block
*/
fun <T : HttpClientEngineConfig> HttpClientConfig<T>.engine(
block: T.() -> Unit
)
/**
* Base configuration for HTTP client engines
*/
open class HttpClientEngineConfig {
/** Number of threads for the engine */
var threadsCount: Int = 4
/** Whether to enable HTTP pipelining */
var pipelining: Boolean = false
/** Proxy configuration */
var proxy: ProxyConfig? = null
}Install and configure client plugins.
/**
* Install a plugin in the HTTP client
* @param plugin - The plugin to install
* @param configure - Configuration block for the plugin
*/
fun <TConfig : Any, TPlugin : Any> HttpClientConfig<*>.install(
plugin: HttpClientPlugin<TConfig, TPlugin>,
configure: TConfig.() -> Unit = {}
)
/**
* Install a plugin by key
* @param key - The plugin key
* @param block - Configuration block
*/
fun <T : Any> HttpClientConfig<*>.install(
key: AttributeKey<T>,
block: () -> T
)Usage Examples:
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
val client = HttpClient {
// Install logging plugin
install(Logging) {
level = LogLevel.INFO
logger = Logger.DEFAULT
}
// Install content negotiation
install(ContentNegotiation) {
json()
}
// Install default request plugin
install(DefaultRequest) {
header("User-Agent", "MyApp/1.0")
host = "api.example.com"
port = 443
}
}Configure HTTP proxy settings.
/**
* Proxy configuration for HTTP client
*/
class ProxyConfig(
val url: Url
) {
constructor(host: String, port: Int) : this(URLBuilder().apply {
this.host = host
this.port = port
}.build())
}
/**
* Types of proxy configurations
*/
enum class ProxyType {
HTTP, HTTPS, SOCKS
}Usage Examples:
val client = HttpClient(CIO) {
engine {
proxy = ProxyConfig("proxy.example.com", 8080)
}
}Manage client lifecycle and resources.
/**
* Close the HTTP client and release resources
*/
suspend fun HttpClient.close()
/**
* Check if the client is closed
*/
val HttpClient.isClosed: BooleanUsage Examples:
val client = HttpClient()
try {
// Use client for requests
val response = client.get("https://api.example.com")
} finally {
// Always close the client
client.close()
}
// Or use with try-with-resources pattern
HttpClient().use { client ->
val response = client.get("https://api.example.com")
// Client automatically closed
}Set default parameters for all requests.
/**
* Default request configuration plugin
*/
object DefaultRequest : HttpClientPlugin<DefaultRequest.Config, DefaultRequest>
/**
* Configuration for default request parameters
*/
class DefaultRequest.Config {
/** Default host */
var host: String? = null
/** Default port */
var port: Int? = null
/** Default headers */
val headers: HeadersBuilder = HeadersBuilder()
/** Default URL parameters */
val url: URLBuilder = URLBuilder()
}Advanced client configuration options and utilities.
/**
* Configure client with engine factory
*/
fun <T : HttpClientEngineConfig> HttpClient(
engineFactory: HttpClientEngineFactory<T>,
block: HttpClientConfig<T>.() -> Unit = {}
): HttpClient
/**
* Access client configuration after creation
*/
fun <T : HttpClientEngineConfig> HttpClient.config(
block: HttpClientConfig<T>.() -> Unit
): HttpClient
/**
* Check if client supports a specific capability
*/
fun HttpClient.isSupported(capability: HttpClientEngineCapability<*>): Boolean
/**
* Access client attributes
*/
val HttpClient.attributes: Attributes
/**
* Access client monitor for events
*/
val HttpClient.monitor: Events
/**
* Access client's engine configuration
*/
val HttpClient.engineConfig: HttpClientEngineConfig
/**
* Access client request pipeline
*/
val HttpClient.requestPipeline: HttpRequestPipeline
/**
* Access client response pipeline
*/
val HttpClient.responsePipeline: HttpResponsePipeline
/**
* Access client send pipeline
*/
val HttpClient.sendPipeline: HttpSendPipeline
/**
* Access client receive pipeline
*/
val HttpClient.receivePipeline: HttpReceivePipelineUsage Examples:
val client = HttpClient(CIO) {
expectSuccess = false
followRedirects = false
}
// Check capabilities
if (client.isSupported(HttpTimeout)) {
println("Client supports timeout configuration")
}
// Access client attributes
client.attributes.put(MyCustomKey, "custom-value")
// Access pipelines for custom interceptors
client.requestPipeline.intercept(HttpRequestPipeline.Before) {
// Custom request processing
}// Engine factory and configuration types
interface HttpClientEngineFactory<T : HttpClientEngineConfig> {
fun create(block: T.() -> Unit = {}): HttpClientEngine
}
// Pipeline types
class HttpRequestPipeline : Pipeline<Any, HttpRequestBuilder>
class HttpResponsePipeline : Pipeline<HttpResponseContainer, HttpClientCall>
class HttpSendPipeline : Pipeline<Any, HttpRequestBuilder>
class HttpReceivePipeline : Pipeline<HttpResponseContainer, HttpClientCall>
// Configuration types
class HttpClientEngineContainer {
companion object {
val default: HttpClientEngine
}
}
// Client lifecycle types
interface Closeable {
fun close()
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-client-core-jvm