0
# Ktor HTTP Client Core
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: io.ktor:ktor-client-core
7
- **Package Type**: Maven (Kotlin Multiplatform)
8
- **Language**: Kotlin
9
- **Targets**: JVM, Android, JS, Native (iOS, macOS, Linux, Windows), WASM
10
- **Installation**: Add to your `build.gradle.kts` dependencies
11
12
```kotlin
13
dependencies {
14
implementation("io.ktor:ktor-client-core:3.2.0")
15
}
16
```
17
18
## Core Imports
19
20
```kotlin
21
import io.ktor.client.*
22
import io.ktor.client.request.*
23
import io.ktor.client.statement.*
24
import io.ktor.client.call.*
25
```
26
27
For plugins:
28
```kotlin
29
import io.ktor.client.plugins.*
30
import io.ktor.client.plugins.cookies.*
31
import io.ktor.client.plugins.websocket.*
32
```
33
34
## Basic Usage
35
36
```kotlin
37
import io.ktor.client.*
38
import io.ktor.client.request.*
39
import io.ktor.client.statement.*
40
41
// Create client
42
val client = HttpClient()
43
44
// Make GET request
45
val response: HttpResponse = client.get("https://api.example.com/users")
46
val responseBody = response.bodyAsText()
47
48
// Make POST request with JSON
49
val postResponse = client.post("https://api.example.com/users") {
50
setBody("""{"name": "John", "email": "john@example.com"}""")
51
header("Content-Type", "application/json")
52
}
53
54
// Always close the client when done
55
client.close()
56
```
57
58
## Architecture
59
60
Ktor Client Core is built around several key components:
61
62
- **HttpClient**: Main client class providing HTTP request capabilities
63
- **Engine System**: Pluggable HTTP engines for different platforms and protocols
64
- **Pipeline Architecture**: Request/response processing pipelines with interceptors
65
- **Plugin System**: Extensible plugin architecture for adding functionality (cookies, authentication, etc.)
66
- **Coroutine Integration**: Full suspend function support for asynchronous operations
67
- **Type Safety**: Reified generics and type-safe API throughout
68
69
## Capabilities
70
71
### HTTP Client Creation and Configuration
72
73
Core HttpClient instantiation and configuration with engines, timeouts, and global settings.
74
75
```kotlin { .api }
76
fun HttpClient(block: HttpClientConfig<*>.() -> Unit = {}): HttpClient
77
78
fun <T : HttpClientEngineConfig> HttpClient(
79
engineFactory: HttpClientEngineFactory<T>,
80
block: HttpClientConfig<T>.() -> Unit = {}
81
): HttpClient
82
83
class HttpClientConfig<T : HttpClientEngineConfig> {
84
var followRedirects: Boolean
85
var useDefaultTransformers: Boolean
86
var expectSuccess: Boolean
87
fun engine(block: T.() -> Unit)
88
fun <TBuilder : Any, TPlugin : Any> install(
89
plugin: HttpClientPlugin<TBuilder, TPlugin>,
90
configure: TBuilder.() -> Unit = {}
91
)
92
}
93
```
94
95
[HTTP Client Configuration](./client-configuration.md)
96
97
### HTTP Requests
98
99
Making HTTP requests with all standard methods (GET, POST, PUT, DELETE, etc.) and request customization options.
100
101
```kotlin { .api }
102
suspend fun HttpClient.get(urlString: String): HttpResponse
103
suspend fun HttpClient.post(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
104
suspend fun HttpClient.put(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
105
suspend fun HttpClient.delete(urlString: String, block: HttpRequestBuilder.() -> Unit = {}): HttpResponse
106
107
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse
108
109
class HttpRequestBuilder {
110
fun setBody(body: Any?)
111
fun parameter(key: String, value: Any?)
112
fun header(key: String, value: String)
113
fun headers(block: HeadersBuilder.() -> Unit)
114
fun url(block: URLBuilder.() -> Unit)
115
}
116
```
117
118
[HTTP Requests](./http-requests.md)
119
120
### Response Handling
121
122
Processing HTTP responses including body extraction, status handling, and streaming support.
123
124
```kotlin { .api }
125
interface HttpResponse {
126
val status: HttpStatusCode
127
val headers: Headers
128
val call: HttpClientCall
129
}
130
131
suspend fun HttpResponse.bodyAsText(charset: Charset = Charsets.UTF_8): String
132
suspend fun HttpResponse.bodyAsChannel(): ByteReadChannel
133
suspend inline fun <reified T> HttpResponse.body(): T
134
135
class HttpStatement {
136
suspend fun execute(): HttpResponse
137
suspend fun <T> execute(block: suspend (HttpResponse) -> T): T
138
}
139
```
140
141
[Response Handling](./response-handling.md)
142
143
### Form Data and File Uploads
144
145
Submitting forms, uploading files, and handling multipart data with type-safe builders.
146
147
```kotlin { .api }
148
suspend fun HttpClient.submitForm(
149
url: String,
150
formParameters: Parameters = Parameters.Empty,
151
encodeInQuery: Boolean = false
152
): HttpResponse
153
154
suspend fun HttpClient.submitFormWithBinaryData(
155
url: String,
156
formData: List<PartData>
157
): HttpResponse
158
159
class FormDataContent(formData: Parameters) : OutgoingContent.ByteArrayContent
160
class MultiPartFormDataContent(parts: List<PartData>) : OutgoingContent.WriteChannelContent
161
162
fun formData(block: FormBuilder.() -> Unit): List<PartData>
163
```
164
165
[Form Data and File Uploads](./forms-and-uploads.md)
166
167
### WebSocket Support
168
169
WebSocket client functionality with message handling and connection management.
170
171
```kotlin { .api }
172
suspend fun HttpClient.webSocket(
173
urlString: String,
174
block: suspend DefaultClientWebSocketSession.() -> Unit
175
)
176
177
suspend fun HttpClient.wss(
178
urlString: String,
179
block: suspend DefaultClientWebSocketSession.() -> Unit
180
)
181
182
interface ClientWebSocketSession : WebSocketSession {
183
suspend fun send(frame: Frame)
184
val incoming: ReceiveChannel<Frame>
185
val outgoing: SendChannel<Frame>
186
}
187
```
188
189
[WebSocket Support](./websockets.md)
190
191
### Server-Sent Events (SSE)
192
193
Server-Sent Events client implementation for real-time event streaming.
194
195
```kotlin { .api }
196
suspend fun HttpClient.sse(
197
urlString: String,
198
block: suspend ClientSSESession.() -> Unit
199
)
200
201
interface ClientSSESession {
202
val incoming: ReceiveChannel<ServerSentEvent>
203
}
204
205
data class ServerSentEvent(
206
val data: String?,
207
val event: String?,
208
val id: String?,
209
val retry: Long?,
210
val comments: String?
211
)
212
```
213
214
[Server-Sent Events](./server-sent-events.md)
215
216
### Plugin System
217
218
Comprehensive plugin architecture with built-in plugins for common functionality and custom plugin creation.
219
220
```kotlin { .api }
221
interface HttpClientPlugin<TBuilder : Any, TPlugin : Any> {
222
val key: AttributeKey<TPlugin>
223
fun prepare(block: TBuilder.() -> Unit): TPlugin
224
fun install(plugin: TPlugin, scope: HttpClient)
225
}
226
227
object HttpTimeout : HttpClientPlugin<HttpTimeoutConfig, HttpTimeoutConfig>
228
object HttpCookies : HttpClientPlugin<HttpCookiesConfig, HttpCookiesConfig>
229
object HttpRedirect : HttpClientPlugin<HttpRedirectConfig, HttpRedirectConfig>
230
231
fun <TConfig : Any, TPlugin : Any> createClientPlugin(
232
name: String,
233
createConfiguration: () -> TConfig,
234
body: ClientPluginBuilder<TConfig>.() -> TPlugin
235
): HttpClientPlugin<TConfig, TPlugin>
236
```
237
238
[Plugin System](./plugin-system.md)
239
240
### Cookie Management
241
242
HTTP cookie handling with multiple storage implementations and automatic cookie management.
243
244
```kotlin { .api }
245
interface CookiesStorage {
246
suspend fun get(requestUrl: Url): List<Cookie>
247
suspend fun addCookie(requestUrl: Url, cookie: Cookie)
248
}
249
250
class AcceptAllCookiesStorage : CookiesStorage
251
class ConstantCookiesStorage(cookies: List<Cookie>) : CookiesStorage
252
253
fun HttpClient.cookies(urlString: String): List<Cookie>
254
```
255
256
[Cookie Management](./cookie-management.md)
257
258
### HTTP Caching
259
260
HTTP response caching with configurable storage and cache control handling.
261
262
```kotlin { .api }
263
interface HttpCacheStorage {
264
suspend fun find(url: Url, varyKeys: Map<String, String>): HttpCacheEntry?
265
suspend fun store(url: Url, data: HttpCacheEntry)
266
}
267
268
class HttpCacheEntry(
269
val url: Url,
270
val statusCode: HttpStatusCode,
271
val requestTime: GMTDate,
272
val responseTime: GMTDate,
273
val version: HttpProtocolVersion,
274
val expires: GMTDate,
275
val headers: Headers,
276
val body: ByteArray
277
)
278
```
279
280
[HTTP Caching](./http-caching.md)
281
282
## Types
283
284
### Core Types
285
286
```kotlin { .api }
287
class HttpClient(
288
val engine: HttpClientEngine,
289
private val userConfig: HttpClientConfig<out HttpClientEngineConfig>
290
) : CoroutineScope, Closeable {
291
val requestPipeline: HttpRequestPipeline
292
val responsePipeline: HttpResponsePipeline
293
val sendPipeline: HttpSendPipeline
294
val receivePipeline: HttpReceivePipeline
295
val attributes: Attributes
296
val engineConfig: HttpClientEngineConfig
297
val monitor: Events
298
299
fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
300
fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
301
override fun close()
302
}
303
304
interface HttpClientCall {
305
val client: HttpClient
306
val request: HttpRequest
307
val response: HttpResponse
308
val attributes: Attributes
309
}
310
311
sealed class RequestBody {
312
object Empty : RequestBody()
313
class ByteArrayContent(val bytes: ByteArray) : RequestBody()
314
class ChannelContent(val channel: ByteReadChannel) : RequestBody()
315
}
316
```
317
318
### Engine Types
319
320
```kotlin { .api }
321
interface HttpClientEngine : CoroutineScope, Closeable {
322
val config: HttpClientEngineConfig
323
val supportedCapabilities: Set<HttpClientEngineCapability<*>>
324
suspend fun execute(data: HttpRequestData): HttpResponseData
325
}
326
327
open class HttpClientEngineConfig {
328
var connectTimeout: Long
329
var socketTimeout: Long
330
var requestTimeout: Long
331
var threadsCount: Int
332
var pipelining: Boolean
333
var proxy: ProxyConfig?
334
}
335
336
interface HttpClientEngineFactory<T : HttpClientEngineConfig> {
337
fun create(block: T.() -> Unit = {}): HttpClientEngine
338
}
339
```