0
# Ktor HTTP Client Core
1
2
Ktor HTTP Client Core is a multiplatform asynchronous HTTP client library for Kotlin that enables developers to make HTTP requests and handle responses across JVM, JavaScript, and Native platforms. The library features a plugin-based architecture, type-safe request building through DSL syntax, full coroutine support, and extensive configuration options for timeouts, redirects, cookies, caching, and WebSocket connections.
3
4
## Package Information
5
6
- **Package Name**: io.ktor:ktor-client-core-iosx64
7
- **Package Type**: Maven
8
- **Language**: Kotlin Multiplatform
9
- **Installation**: Add dependency to your build.gradle.kts:
10
11
```kotlin
12
dependencies {
13
implementation("io.ktor:ktor-client-core:2.3.13")
14
// Also add a specific engine implementation
15
implementation("io.ktor:ktor-client-cio:2.3.13") // For JVM
16
}
17
```
18
19
## Core Imports
20
21
```kotlin
22
import io.ktor.client.*
23
import io.ktor.client.request.*
24
import io.ktor.client.statement.*
25
import io.ktor.client.engine.cio.*
26
```
27
28
## Basic Usage
29
30
```kotlin
31
import io.ktor.client.*
32
import io.ktor.client.request.*
33
import io.ktor.client.statement.*
34
import io.ktor.client.engine.cio.*
35
36
// Create HTTP client
37
val client = HttpClient(CIO) {
38
// Optional configuration
39
}
40
41
// Make GET request
42
val response: HttpResponse = client.get("https://api.example.com/users")
43
val content: String = response.bodyAsText()
44
45
// Make POST request with JSON
46
val postResponse = client.post("https://api.example.com/users") {
47
contentType(ContentType.Application.Json)
48
setBody("""{"name": "John", "email": "john@example.com"}""")
49
}
50
51
// Clean up
52
client.close()
53
```
54
55
## Architecture
56
57
Ktor HTTP Client Core is built around several key components:
58
59
- **HttpClient**: Main client class implementing CoroutineScope for structured concurrency
60
- **HttpClientEngine**: Platform-specific engine abstraction for actual HTTP operations
61
- **Request Pipeline**: Configurable pipeline for processing outgoing requests
62
- **Response Pipeline**: Configurable pipeline for processing incoming responses
63
- **Plugin System**: Extensible architecture for adding functionality like authentication, caching, and logging
64
- **Type-Safe DSL**: Kotlin DSL for building requests with compile-time safety
65
- **Multiplatform Design**: Common API with platform-specific optimizations
66
67
## Capabilities
68
69
### HTTP Client Creation and Configuration
70
71
Core functionality for creating and configuring HTTP clients with engine selection and plugin installation.
72
73
```kotlin { .api }
74
// Primary client factory function (platform-specific)
75
expect fun HttpClient(
76
block: HttpClientConfig<*>.() -> Unit = {}
77
): HttpClient
78
79
// Client factory with engine
80
fun <T : HttpClientEngineConfig> HttpClient(
81
engineFactory: HttpClientEngineFactory<T>,
82
block: HttpClientConfig<T>.() -> Unit = {}
83
): HttpClient
84
85
// Client with existing engine
86
fun HttpClient(
87
engine: HttpClientEngine,
88
block: HttpClientConfig<*>.() -> Unit
89
): HttpClient
90
91
class HttpClient(
92
val engine: HttpClientEngine,
93
private val userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()
94
) : CoroutineScope, Closeable {
95
val requestPipeline: HttpRequestPipeline
96
val responsePipeline: HttpResponsePipeline
97
val sendPipeline: HttpSendPipeline
98
val receivePipeline: HttpReceivePipeline
99
val attributes: Attributes
100
val engineConfig: HttpClientEngineConfig
101
val monitor: Events
102
103
fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
104
fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
105
override fun close()
106
}
107
```
108
109
[Client Configuration](./client-configuration.md)
110
111
### HTTP Request Building and Execution
112
113
Type-safe DSL for building and executing HTTP requests with all standard HTTP methods.
114
115
```kotlin { .api }
116
// Generic request functions
117
suspend fun HttpClient.request(
118
builder: HttpRequestBuilder = HttpRequestBuilder()
119
): HttpResponse
120
121
suspend fun HttpClient.request(
122
block: HttpRequestBuilder.() -> Unit
123
): HttpResponse
124
125
suspend fun HttpClient.request(
126
urlString: String,
127
block: HttpRequestBuilder.() -> Unit = {}
128
): HttpResponse
129
130
// HTTP method convenience functions
131
suspend fun HttpClient.get(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
132
suspend fun HttpClient.post(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
133
suspend fun HttpClient.put(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
134
suspend fun HttpClient.delete(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
135
suspend fun HttpClient.patch(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
136
suspend fun HttpClient.head(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
137
suspend fun HttpClient.options(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
138
139
class HttpRequestBuilder {
140
var url: URLBuilder
141
var method: HttpMethod
142
var headers: HeadersBuilder
143
var body: Any
144
var attributes: Attributes
145
146
fun url(block: URLBuilder.() -> Unit)
147
fun build(): HttpRequestData
148
fun takeFrom(builder: HttpRequestBuilder): HttpRequestBuilder
149
}
150
151
// Progress tracking extensions
152
typealias ProgressListener = suspend (bytesSentTotal: Long, contentLength: Long) -> Unit
153
fun HttpRequestBuilder.onUpload(listener: ProgressListener?)
154
fun HttpRequestBuilder.onDownload(listener: ProgressListener?)
155
156
// Timeout configuration extension
157
fun HttpRequestBuilder.timeout(block: HttpTimeout.HttpTimeoutCapabilityConfiguration.() -> Unit)
158
159
// Retry configuration extension
160
fun HttpRequestBuilder.retry(block: HttpRequestRetry.Configuration.() -> Unit)
161
```
162
163
[Request Building](./request-building.md)
164
165
### HTTP Response Handling
166
167
Comprehensive response handling with typed body access and streaming capabilities.
168
169
```kotlin { .api }
170
// Response classes
171
abstract class HttpResponse : HttpMessage, CoroutineScope {
172
abstract val call: HttpClientCall
173
abstract val status: HttpStatusCode
174
abstract val version: HttpProtocolVersion
175
abstract val requestTime: GMTDate
176
abstract val responseTime: GMTDate
177
abstract val content: ByteReadChannel
178
}
179
180
// Response body access
181
suspend fun HttpResponse.bodyAsText(fallbackCharset: Charset = Charsets.UTF_8): String
182
suspend fun HttpResponse.bodyAsChannel(): ByteReadChannel
183
suspend inline fun <reified T> HttpResponse.body(): T
184
185
// Prepared statements
186
class HttpStatement(
187
private val builder: HttpRequestBuilder,
188
private val client: HttpClient
189
) {
190
suspend fun <T> execute(block: suspend (response: HttpResponse) -> T): T
191
suspend fun execute(): HttpResponse
192
suspend inline fun <reified T> body(): T
193
}
194
195
// Client call representation
196
class HttpClientCall(
197
val client: HttpClient
198
) : CoroutineScope {
199
val attributes: Attributes
200
val request: HttpRequest
201
val response: HttpResponse
202
203
suspend inline fun <reified T> body(): T
204
suspend fun bodyNullable(info: TypeInfo): Any?
205
}
206
```
207
208
[Response Handling](./response-handling.md)
209
210
### Plugin System
211
212
Extensible plugin architecture for adding cross-cutting concerns like authentication, caching, and logging.
213
214
```kotlin { .api }
215
interface HttpClientPlugin<out TConfig : Any, TPlugin : Any> {
216
val key: AttributeKey<TPlugin>
217
218
fun prepare(block: TConfig.() -> Unit = {}): TPlugin
219
fun install(plugin: TPlugin, scope: HttpClient)
220
}
221
222
// Plugin access
223
fun <B : Any, F : Any> HttpClient.pluginOrNull(plugin: HttpClientPlugin<B, F>): F?
224
fun <B : Any, F : Any> HttpClient.plugin(plugin: HttpClientPlugin<B, F>): F
225
226
// Configuration in client
227
class HttpClientConfig<T : HttpClientEngineConfig> {
228
fun <TBuilder : Any, TPlugin : Any> install(
229
plugin: HttpClientPlugin<TBuilder, TPlugin>,
230
configure: TBuilder.() -> Unit = {}
231
)
232
fun install(key: String, block: HttpClient.() -> Unit)
233
}
234
```
235
236
[Plugin System](./plugin-system.md)
237
238
### Engine Abstraction
239
240
Platform-specific engine abstraction providing the underlying HTTP implementation.
241
242
```kotlin { .api }
243
interface HttpClientEngine : CoroutineScope, Closeable {
244
val dispatcher: CoroutineDispatcher
245
val config: HttpClientEngineConfig
246
val supportedCapabilities: Set<HttpClientEngineCapability<*>>
247
}
248
249
interface HttpClientEngineFactory<out T : HttpClientEngineConfig> {
250
fun create(block: T.() -> Unit = {}): HttpClientEngine
251
}
252
253
open class HttpClientEngineConfig {
254
var threadsCount: Int = 4 // Deprecated
255
var pipelining: Boolean = false
256
var proxy: ProxyConfig? = null
257
}
258
```
259
260
[Engine Configuration](./engine-configuration.md)
261
262
### WebSocket Support
263
264
Full-duplex WebSocket communication with extensions support and content conversion.
265
266
```kotlin { .api }
267
object WebSockets : HttpClientPlugin<WebSockets.Config, WebSockets> {
268
class Config {
269
var pingInterval: Long = -1L
270
var maxFrameSize: Long = Long.MAX_VALUE
271
var contentConverter: WebsocketContentConverter? = null
272
273
fun extensions(block: WebSocketExtensionsConfig.() -> Unit)
274
}
275
}
276
277
// WebSocket connection functions
278
suspend fun HttpClient.webSocketSession(
279
block: HttpRequestBuilder.() -> Unit
280
): DefaultClientWebSocketSession
281
282
suspend fun HttpClient.webSocket(
283
urlString: String,
284
request: HttpRequestBuilder.() -> Unit = {},
285
block: suspend DefaultClientWebSocketSession.() -> Unit
286
)
287
288
suspend fun HttpClient.ws(
289
urlString: String,
290
request: HttpRequestBuilder.() -> Unit = {},
291
block: suspend DefaultClientWebSocketSession.() -> Unit
292
)
293
```
294
295
[WebSocket Support](./websocket-support.md)
296
297
### Form Handling
298
299
Support for URL-encoded forms and multipart form data with file uploads.
300
301
```kotlin { .api }
302
// Form content classes
303
class FormDataContent(val formData: Parameters) : OutgoingContent.ByteArrayContent() {
304
override val contentLength: Long
305
override val contentType: ContentType
306
override fun bytes(): ByteArray
307
}
308
309
class MultiPartFormDataContent(
310
parts: List<PartData>,
311
boundary: String,
312
contentType: ContentType = ContentType.MultiPart.FormData.withParameter("boundary", boundary)
313
) : OutgoingContent.WriteChannelContent() {
314
val boundary: String
315
override val contentType: ContentType
316
override val contentLength: Long?
317
}
318
319
// Form submission functions
320
suspend fun HttpClient.submitForm(
321
formParameters: Parameters,
322
encodeInQuery: Boolean = false,
323
block: HttpRequestBuilder.() -> Unit = {}
324
): HttpResponse
325
326
suspend fun HttpClient.submitFormWithBinaryData(
327
formData: List<PartData>,
328
block: HttpRequestBuilder.() -> Unit = {}
329
): HttpResponse
330
```
331
332
[Form Handling](./form-handling.md)
333
334
### Cookie Management
335
336
Cookie storage and management with configurable storage backends.
337
338
```kotlin { .api }
339
class HttpCookies private constructor(
340
private val storage: CookiesStorage
341
) : Closeable {
342
class Config {
343
var storage: CookiesStorage = AcceptAllCookiesStorage()
344
345
fun default(block: suspend CookiesStorage.() -> Unit)
346
}
347
348
companion object : HttpClientPlugin<Config, HttpCookies> {
349
override val key: AttributeKey<HttpCookies> = AttributeKey("HttpCookies")
350
}
351
352
suspend fun get(requestUrl: Url): List<Cookie>
353
}
354
355
interface CookiesStorage : Closeable {
356
suspend fun get(requestUrl: Url): List<Cookie>
357
suspend fun addCookie(requestUrl: Url, cookie: Cookie)
358
}
359
360
class AcceptAllCookiesStorage : CookiesStorage
361
class ConstantCookiesStorage(cookies: List<Cookie>) : CookiesStorage
362
```
363
364
[Cookie Management](./cookie-management.md)
365
366
### HTTP Caching
367
368
Response caching with configurable storage backends and cache control support.
369
370
```kotlin { .api }
371
class HttpCache internal constructor(
372
private val publicStorage: CacheStorage,
373
private val privateStorage: CacheStorage,
374
private val isSharedClient: Boolean
375
) {
376
class Config {
377
var isShared: Boolean = false
378
379
fun publicStorage(storage: CacheStorage)
380
fun privateStorage(storage: CacheStorage)
381
}
382
383
companion object : HttpClientPlugin<Config, HttpCache> {
384
override val key: AttributeKey<HttpCache> = AttributeKey("HttpCache")
385
val HttpResponseFromCache: EventDefinition<HttpResponse>
386
}
387
}
388
389
interface CacheStorage {
390
suspend fun store(url: Url, data: CachedResponseData)
391
suspend fun find(url: Url, varyKeys: Map<String, String>): CachedResponseData?
392
suspend fun findAll(url: Url): Set<CachedResponseData>
393
394
companion object {
395
fun Unlimited(): CacheStorage
396
val Disabled: CacheStorage
397
}
398
}
399
400
data class CachedResponseData(
401
val url: Url,
402
val statusCode: HttpStatusCode,
403
val requestTime: GMTDate,
404
val responseTime: GMTDate,
405
val version: HttpProtocolVersion,
406
val expires: GMTDate,
407
val headers: Headers,
408
val varyKeys: Map<String, String>,
409
val body: ByteArray
410
)
411
```
412
413
[HTTP Caching](./http-caching.md)
414
415
## Types
416
417
### Core Types
418
419
```kotlin { .api }
420
// Request types
421
interface HttpRequest : HttpMessage {
422
val call: HttpClientCall
423
val method: HttpMethod
424
val url: Url
425
val attributes: Attributes
426
val content: OutgoingContent
427
}
428
429
data class HttpRequestData(
430
val url: Url,
431
val method: HttpMethod,
432
val headers: Headers,
433
val body: OutgoingContent,
434
val executionContext: Job,
435
val attributes: Attributes
436
)
437
438
data class HttpResponseData(
439
val statusCode: HttpStatusCode,
440
val requestTime: GMTDate,
441
val headers: Headers,
442
val version: HttpProtocolVersion,
443
val body: ByteReadChannel,
444
val callContext: CoroutineContext
445
)
446
447
// Pipeline types
448
class HttpRequestPipeline(developmentMode: Boolean = false)
449
class HttpResponsePipeline(developmentMode: Boolean = false)
450
class HttpSendPipeline(developmentMode: Boolean = false)
451
class HttpReceivePipeline(developmentMode: Boolean = false)
452
453
// Engine capability
454
interface HttpClientEngineCapability<T>
455
456
// Proxy configuration
457
expect class ProxyConfig
458
459
enum class ProxyType {
460
SOCKS, HTTP, UNKNOWN
461
}
462
463
expect object ProxyBuilder {
464
fun http(url: Url): ProxyConfig
465
fun http(urlString: String): ProxyConfig
466
fun socks(host: String, port: Int): ProxyConfig
467
}
468
```
469
470
## Exception Classes
471
472
```kotlin { .api }
473
// Request/Response exceptions
474
class DoubleReceiveException(message: String) : IllegalStateException(message)
475
class ReceivePipelineException(message: String, cause: Throwable) : IllegalStateException(message, cause)
476
class NoTransformationFoundException(from: KType, to: KType) : UnsupportedOperationException()
477
478
// Timeout exceptions
479
class HttpRequestTimeoutException(url: String, timeoutMillis: Long?) : IOException()
480
fun ConnectTimeoutException(request: HttpRequestData, cause: Throwable? = null): ConnectTimeoutException
481
fun ConnectTimeoutException(url: String, timeout: Long?, cause: Throwable? = null): ConnectTimeoutException
482
fun SocketTimeoutException(request: HttpRequestData, cause: Throwable? = null): SocketTimeoutException
483
484
// Plugin validation exceptions
485
class ResponseException(response: HttpResponse, cachedResponseText: String) : IllegalStateException()
486
class RedirectResponseException(response: HttpResponse, message: String) : ResponseException(response, message)
487
class ClientRequestException(response: HttpResponse, message: String) : ResponseException(response, message)
488
class ServerResponseException(response: HttpResponse, message: String) : ResponseException(response, message)
489
490
// Retry exceptions
491
class SendCountExceedException(message: String) : IllegalStateException(message)
492
493
// WebSocket exceptions
494
open class WebSocketException(message: String) : IllegalStateException(message)
495
496
// Cache exceptions
497
class InvalidCacheStateException(message: String) : IllegalStateException(message)
498
```
499
500
## Event Definitions
501
502
```kotlin { .api }
503
val HttpRequestCreated: EventDefinition<HttpRequestBuilder>
504
val HttpRequestIsReadyForSending: EventDefinition<HttpRequestBuilder>
505
val HttpResponseReceived: EventDefinition<HttpResponse>
506
val HttpResponseReceiveFailed: EventDefinition<HttpResponseReceiveFail>
507
val HttpResponseCancelled: EventDefinition<HttpResponse>
508
val HttpRequestRetryEvent: EventDefinition<HttpRequestRetry.RetryEventData>
509
510
data class HttpResponseReceiveFail(
511
val response: HttpResponse,
512
val cause: Throwable
513
)
514
```