Ktor HTTP Client Core - a multiplatform asynchronous HTTP client library for Kotlin providing comprehensive HTTP request/response handling with plugin architecture.
npx @tessl/cli install tessl/maven-io-ktor--ktor-client-core@3.2.0Ktor HTTP Client Core is an asynchronous HTTP client library for Kotlin Multiplatform that provides comprehensive functionality for making HTTP requests, handling responses, and extending capabilities through plugins. This multiplatform library enables HTTP communication across all Kotlin targets with full coroutine support and type safety.
build.gradle.kts dependenciesdependencies {
implementation("io.ktor:ktor-client-core:3.2.0")
}import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.call.*For plugins:
import io.ktor.client.plugins.*
import io.ktor.client.plugins.cookies.*
import io.ktor.client.plugins.websocket.*import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
// Create client
val client = HttpClient()
// Make GET request
val response: HttpResponse = client.get("https://api.example.com/users")
val responseBody = response.bodyAsText()
// Make POST request with JSON
val postResponse = client.post("https://api.example.com/users") {
setBody("""{"name": "John", "email": "john@example.com"}""")
header("Content-Type", "application/json")
}
// Always close the client when done
client.close()Ktor Client Core is built around several key components:
Core HttpClient instantiation and configuration with engines, timeouts, and global settings.
fun HttpClient(block: HttpClientConfig<*>.() -> Unit = {}): HttpClient
fun <T : HttpClientEngineConfig> HttpClient(
engineFactory: HttpClientEngineFactory<T>,
block: HttpClientConfig<T>.() -> Unit = {}
): HttpClient
class HttpClientConfig<T : HttpClientEngineConfig> {
var followRedirects: Boolean
var useDefaultTransformers: Boolean
var expectSuccess: Boolean
fun engine(block: T.() -> Unit)
fun <TBuilder : Any, TPlugin : Any> install(
plugin: HttpClientPlugin<TBuilder, TPlugin>,
configure: TBuilder.() -> Unit = {}
)
}Making HTTP requests with all standard methods (GET, POST, PUT, DELETE, etc.) and request customization options.
suspend fun HttpClient.get(urlString: String): HttpResponse
suspend fun HttpClient.post(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
suspend fun HttpClient.put(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
suspend fun HttpClient.delete(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse
class HttpRequestBuilder {
fun setBody(body: Any?)
fun parameter(key: String, value: Any?)
fun header(key: String, value: String)
fun headers(block: HeadersBuilder.() -> Unit)
fun url(block: URLBuilder.() -> Unit)
}Processing HTTP responses including body extraction, status handling, and streaming support.
interface HttpResponse {
val status: HttpStatusCode
val headers: Headers
val call: HttpClientCall
}
suspend fun HttpResponse.bodyAsText(charset: Charset = Charsets.UTF_8): String
suspend fun HttpResponse.bodyAsChannel(): ByteReadChannel
suspend inline fun <reified T> HttpResponse.body(): T
class HttpStatement {
suspend fun execute(): HttpResponse
suspend fun <T> execute(block: suspend (HttpResponse) -> T): T
}Submitting forms, uploading files, and handling multipart data with type-safe builders.
suspend fun HttpClient.submitForm(
url: String,
formParameters: Parameters = Parameters.Empty,
encodeInQuery: Boolean = false
): HttpResponse
suspend fun HttpClient.submitFormWithBinaryData(
url: String,
formData: List<PartData>
): HttpResponse
class FormDataContent(formData: Parameters) : OutgoingContent.ByteArrayContent
class MultiPartFormDataContent(parts: List<PartData>) : OutgoingContent.WriteChannelContent
fun formData(block: FormBuilder.() -> Unit): List<PartData>WebSocket client functionality with message handling and connection management.
suspend fun HttpClient.webSocket(
urlString: String,
block: suspend DefaultClientWebSocketSession.() -> Unit
)
suspend fun HttpClient.wss(
urlString: String,
block: suspend DefaultClientWebSocketSession.() -> Unit
)
interface ClientWebSocketSession : WebSocketSession {
suspend fun send(frame: Frame)
val incoming: ReceiveChannel<Frame>
val outgoing: SendChannel<Frame>
}Server-Sent Events client implementation for real-time event streaming.
suspend fun HttpClient.sse(
urlString: String,
block: suspend ClientSSESession.() -> Unit
)
interface ClientSSESession {
val incoming: ReceiveChannel<ServerSentEvent>
}
data class ServerSentEvent(
val data: String?,
val event: String?,
val id: String?,
val retry: Long?,
val comments: String?
)Comprehensive plugin architecture with built-in plugins for common functionality and custom plugin creation.
interface HttpClientPlugin<TBuilder : Any, TPlugin : Any> {
val key: AttributeKey<TPlugin>
fun prepare(block: TBuilder.() -> Unit): TPlugin
fun install(plugin: TPlugin, scope: HttpClient)
}
object HttpTimeout : HttpClientPlugin<HttpTimeoutConfig, HttpTimeoutConfig>
object HttpCookies : HttpClientPlugin<HttpCookiesConfig, HttpCookiesConfig>
object HttpRedirect : HttpClientPlugin<HttpRedirectConfig, HttpRedirectConfig>
fun <TConfig : Any, TPlugin : Any> createClientPlugin(
name: String,
createConfiguration: () -> TConfig,
body: ClientPluginBuilder<TConfig>.() -> TPlugin
): HttpClientPlugin<TConfig, TPlugin>HTTP cookie handling with multiple storage implementations and automatic cookie management.
interface CookiesStorage {
suspend fun get(requestUrl: Url): List<Cookie>
suspend fun addCookie(requestUrl: Url, cookie: Cookie)
}
class AcceptAllCookiesStorage : CookiesStorage
class ConstantCookiesStorage(cookies: List<Cookie>) : CookiesStorage
fun HttpClient.cookies(urlString: String): List<Cookie>HTTP response caching with configurable storage and cache control handling.
interface HttpCacheStorage {
suspend fun find(url: Url, varyKeys: Map<String, String>): HttpCacheEntry?
suspend fun store(url: Url, data: HttpCacheEntry)
}
class HttpCacheEntry(
val url: Url,
val statusCode: HttpStatusCode,
val requestTime: GMTDate,
val responseTime: GMTDate,
val version: HttpProtocolVersion,
val expires: GMTDate,
val headers: Headers,
val body: ByteArray
)class HttpClient(
val engine: HttpClientEngine,
private val userConfig: HttpClientConfig<out HttpClientEngineConfig>
) : CoroutineScope, Closeable {
val requestPipeline: HttpRequestPipeline
val responsePipeline: HttpResponsePipeline
val sendPipeline: HttpSendPipeline
val receivePipeline: HttpReceivePipeline
val attributes: Attributes
val engineConfig: HttpClientEngineConfig
val monitor: Events
fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
override fun close()
}
interface HttpClientCall {
val client: HttpClient
val request: HttpRequest
val response: HttpResponse
val attributes: Attributes
}
sealed class RequestBody {
object Empty : RequestBody()
class ByteArrayContent(val bytes: ByteArray) : RequestBody()
class ChannelContent(val channel: ByteReadChannel) : RequestBody()
}interface HttpClientEngine : CoroutineScope, Closeable {
val config: HttpClientEngineConfig
val supportedCapabilities: Set<HttpClientEngineCapability<*>>
suspend fun execute(data: HttpRequestData): HttpResponseData
}
open class HttpClientEngineConfig {
var connectTimeout: Long
var socketTimeout: Long
var requestTimeout: Long
var threadsCount: Int
var pipelining: Boolean
var proxy: ProxyConfig?
}
interface HttpClientEngineFactory<T : HttpClientEngineConfig> {
fun create(block: T.() -> Unit = {}): HttpClientEngine
}