or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-configuration.mdcookie-management.mdforms-and-uploads.mdhttp-caching.mdhttp-requests.mdindex.mdplugin-system.mdresponse-handling.mdserver-sent-events.mdwebsockets.md
tile.json

tessl/maven-io-ktor--ktor-client-core

Ktor HTTP Client Core - a multiplatform asynchronous HTTP client library for Kotlin providing comprehensive HTTP request/response handling with plugin architecture.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.ktor/ktor-client-core@3.2.x

To install, run

npx @tessl/cli install tessl/maven-io-ktor--ktor-client-core@3.2.0

index.mddocs/

Ktor HTTP Client Core

Ktor 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.

Package Information

  • Package Name: io.ktor:ktor-client-core
  • Package Type: Maven (Kotlin Multiplatform)
  • Language: Kotlin
  • Targets: JVM, Android, JS, Native (iOS, macOS, Linux, Windows), WASM
  • Installation: Add to your build.gradle.kts dependencies
dependencies {
    implementation("io.ktor:ktor-client-core:3.2.0")
}

Core Imports

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.*

Basic Usage

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()

Architecture

Ktor Client Core is built around several key components:

  • HttpClient: Main client class providing HTTP request capabilities
  • Engine System: Pluggable HTTP engines for different platforms and protocols
  • Pipeline Architecture: Request/response processing pipelines with interceptors
  • Plugin System: Extensible plugin architecture for adding functionality (cookies, authentication, etc.)
  • Coroutine Integration: Full suspend function support for asynchronous operations
  • Type Safety: Reified generics and type-safe API throughout

Capabilities

HTTP Client Creation and Configuration

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 = {}
    )
}

HTTP Client Configuration

HTTP Requests

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)
}

HTTP Requests

Response Handling

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
}

Response Handling

Form Data and File Uploads

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>

Form Data and File Uploads

WebSocket Support

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>
}

WebSocket Support

Server-Sent Events (SSE)

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?
)

Server-Sent Events

Plugin System

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>

Plugin System

Cookie Management

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>

Cookie Management

HTTP Caching

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
)

HTTP Caching

Types

Core Types

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()
}

Engine Types

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
}