0
# HTTP Client Operations
1
2
Core HTTP client functionality for making requests, handling responses, and managing client lifecycle with multiplatform support and coroutine-based API.
3
4
## Capabilities
5
6
### HttpClient Class
7
8
Main HTTP client class providing HTTP operations with configurable engines and plugins.
9
10
```kotlin { .api }
11
/**
12
* A multiplatform asynchronous HTTP client for making requests and handling responses
13
* @param engine HTTP client engine for platform-specific implementation
14
* @param userConfig Configuration for the client
15
*/
16
class HttpClient(
17
public val engine: HttpClientEngine,
18
private val userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()
19
) : CoroutineScope, Closeable {
20
21
/** Pipeline for processing outgoing requests */
22
public val requestPipeline: HttpRequestPipeline
23
24
/** Pipeline for processing incoming responses */
25
public val responsePipeline: HttpResponsePipeline
26
27
/** Pipeline for sending requests */
28
public val sendPipeline: HttpSendPipeline
29
30
/** Pipeline for receiving responses */
31
public val receivePipeline: HttpReceivePipeline
32
33
/** Client attributes for storing custom data */
34
public val attributes: Attributes
35
36
/** Engine configuration access */
37
public val engineConfig: HttpClientEngineConfig
38
39
/** Event monitoring for client lifecycle */
40
public val monitor: Events
41
42
/** Check if engine supports a specific capability */
43
public fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
44
45
/** Create a new client with additional configuration */
46
public fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
47
48
/** Close the client and release resources */
49
override fun close()
50
}
51
```
52
53
**Usage Examples:**
54
55
```kotlin
56
import io.ktor.client.*
57
import io.ktor.client.engine.cio.*
58
59
// Create client with default engine
60
val client = HttpClient()
61
62
// Create client with specific engine
63
val cioClient = HttpClient(CIO) {
64
expectSuccess = false
65
followRedirects = true
66
}
67
68
// Check engine capabilities
69
if (client.isSupported(HttpTimeout)) {
70
println("Timeout supported")
71
}
72
73
// Create configured client
74
val configuredClient = client.config {
75
install(HttpTimeout) {
76
requestTimeoutMillis = 10000
77
}
78
}
79
80
// Always close clients
81
client.close()
82
configuredClient.close()
83
```
84
85
### HttpClient Factory Function
86
87
Platform-specific factory function for creating HTTP clients with configuration.
88
89
```kotlin { .api }
90
/**
91
* Creates an HttpClient with platform-appropriate default engine
92
* @param block Configuration block for the client
93
* @return Configured HttpClient instance
94
*/
95
expect fun HttpClient(
96
block: HttpClientConfig<*>.() -> Unit = {}
97
): HttpClient
98
```
99
100
**Usage Examples:**
101
102
```kotlin
103
import io.ktor.client.*
104
import io.ktor.client.plugins.*
105
106
// Simple client creation
107
val client = HttpClient()
108
109
// Client with configuration
110
val configuredClient = HttpClient {
111
install(UserAgent) {
112
agent = "MyApp/1.0"
113
}
114
115
expectSuccess = false
116
followRedirects = true
117
118
engine {
119
// Engine-specific configuration
120
threadsCount = 4
121
pipelining = true
122
}
123
}
124
```
125
126
### HTTP Method Extensions
127
128
Convenient extension functions for common HTTP methods.
129
130
```kotlin { .api }
131
/**
132
* Perform GET request
133
* @param urlString Target URL
134
* @param block Request configuration
135
* @return HTTP response
136
*/
137
suspend fun HttpClient.get(
138
urlString: String,
139
block: HttpRequestBuilder.() -> Unit = {}
140
): HttpResponse
141
142
/**
143
* Perform POST request
144
* @param urlString Target URL
145
* @param block Request configuration
146
* @return HTTP response
147
*/
148
suspend fun HttpClient.post(
149
urlString: String,
150
block: HttpRequestBuilder.() -> Unit = {}
151
): HttpResponse
152
153
/**
154
* Perform PUT request
155
* @param urlString Target URL
156
* @param block Request configuration
157
* @return HTTP response
158
*/
159
suspend fun HttpClient.put(
160
urlString: String,
161
block: HttpRequestBuilder.() -> Unit = {}
162
): HttpResponse
163
164
/**
165
* Perform PATCH request
166
* @param urlString Target URL
167
* @param block Request configuration
168
* @return HTTP response
169
*/
170
suspend fun HttpClient.patch(
171
urlString: String,
172
block: HttpRequestBuilder.() -> Unit = {}
173
): HttpResponse
174
175
/**
176
* Perform DELETE request
177
* @param urlString Target URL
178
* @param block Request configuration
179
* @return HTTP response
180
*/
181
suspend fun HttpClient.delete(
182
urlString: String,
183
block: HttpRequestBuilder.() -> Unit = {}
184
): HttpResponse
185
186
/**
187
* Perform HEAD request
188
* @param urlString Target URL
189
* @param block Request configuration
190
* @return HTTP response
191
*/
192
suspend fun HttpClient.head(
193
urlString: String,
194
block: HttpRequestBuilder.() -> Unit = {}
195
): HttpResponse
196
197
/**
198
* Perform OPTIONS request
199
* @param urlString Target URL
200
* @param block Request configuration
201
* @return HTTP response
202
*/
203
suspend fun HttpClient.options(
204
urlString: String,
205
block: HttpRequestBuilder.() -> Unit = {}
206
): HttpResponse
207
```
208
209
**Usage Examples:**
210
211
```kotlin
212
import io.ktor.client.*
213
import io.ktor.client.request.*
214
import io.ktor.client.statement.*
215
216
val client = HttpClient()
217
218
// GET request
219
val getResponse = client.get("https://api.example.com/users")
220
val users = getResponse.bodyAsText()
221
222
// POST request with JSON body
223
val postResponse = client.post("https://api.example.com/users") {
224
setBody("""{"name": "John", "email": "john@example.com"}""")
225
headers {
226
append("Content-Type", "application/json")
227
}
228
}
229
230
// PUT request with authentication
231
val putResponse = client.put("https://api.example.com/users/123") {
232
setBody("""{"name": "John Updated"}""")
233
headers {
234
append("Authorization", "Bearer $token")
235
append("Content-Type", "application/json")
236
}
237
}
238
239
// DELETE request
240
val deleteResponse = client.delete("https://api.example.com/users/123") {
241
headers {
242
append("Authorization", "Bearer $token")
243
}
244
}
245
```
246
247
### Generic Request Function
248
249
Generic request function for custom HTTP methods and advanced configurations.
250
251
```kotlin { .api }
252
/**
253
* Perform generic HTTP request
254
* @param block Request configuration including method, URL, headers, body
255
* @return HTTP response
256
*/
257
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse
258
```
259
260
**Usage Examples:**
261
262
```kotlin
263
import io.ktor.client.*
264
import io.ktor.client.request.*
265
import io.ktor.http.*
266
267
val client = HttpClient()
268
269
// Custom HTTP method
270
val response = client.request {
271
method = HttpMethod("PATCH")
272
url("https://api.example.com/resource")
273
setBody("""{"op": "replace", "path": "/status", "value": "active"}""")
274
headers {
275
append("Content-Type", "application/json-patch+json")
276
}
277
}
278
279
// Complex request configuration
280
val complexResponse = client.request {
281
method = HttpMethod.Post
282
url {
283
protocol = URLProtocol.HTTPS
284
host = "api.example.com"
285
path("v1", "users")
286
parameter("include", "profile")
287
}
288
headers {
289
append("Authorization", "Bearer $token")
290
append("Accept", "application/vnd.api+json")
291
}
292
setBody(requestData)
293
timeout {
294
requestTimeoutMillis = 30000
295
}
296
}
297
```
298
299
### Request Preparation Functions
300
301
Functions for preparing requests without immediate execution.
302
303
```kotlin { .api }
304
/**
305
* Prepare GET request for later execution
306
* @param urlString Target URL
307
* @param block Request configuration
308
* @return Prepared HttpStatement
309
*/
310
suspend fun HttpClient.prepareGet(
311
urlString: String,
312
block: HttpRequestBuilder.() -> Unit = {}
313
): HttpStatement
314
315
/**
316
* Prepare POST request for later execution
317
* @param urlString Target URL
318
* @param block Request configuration
319
* @return Prepared HttpStatement
320
*/
321
suspend fun HttpClient.preparePost(
322
urlString: String,
323
block: HttpRequestBuilder.() -> Unit = {}
324
): HttpStatement
325
326
/**
327
* Prepare PUT request for later execution
328
* @param urlString Target URL
329
* @param block Request configuration
330
* @return Prepared HttpStatement
331
*/
332
suspend fun HttpClient.preparePut(
333
urlString: String,
334
block: HttpRequestBuilder.() -> Unit = {}
335
): HttpStatement
336
337
/**
338
* Prepare DELETE request for later execution
339
* @param urlString Target URL
340
* @param block Request configuration
341
* @return Prepared HttpStatement
342
*/
343
suspend fun HttpClient.prepareDelete(
344
urlString: String,
345
block: HttpRequestBuilder.() -> Unit = {}
346
): HttpStatement
347
348
/**
349
* Prepare HEAD request for later execution
350
* @param urlString Target URL
351
* @param block Request configuration
352
* @return Prepared HttpStatement
353
*/
354
suspend fun HttpClient.prepareHead(
355
urlString: String,
356
block: HttpRequestBuilder.() -> Unit = {}
357
): HttpStatement
358
359
/**
360
* Prepare OPTIONS request for later execution
361
* @param urlString Target URL
362
* @param block Request configuration
363
* @return Prepared HttpStatement
364
*/
365
suspend fun HttpClient.prepareOptions(
366
urlString: String,
367
block: HttpRequestBuilder.() -> Unit = {}
368
): HttpStatement
369
```
370
371
**Usage Examples:**
372
373
```kotlin
374
import io.ktor.client.*
375
import io.ktor.client.statement.*
376
377
val client = HttpClient()
378
379
// Prepare request for reuse
380
val statement = client.prepareGet("https://api.example.com/data") {
381
headers {
382
append("Accept", "application/json")
383
}
384
}
385
386
// Execute multiple times
387
val response1 = statement.execute()
388
val data1 = response1.bodyAsText()
389
390
val response2 = statement.execute()
391
val data2 = response2.bodyAsText()
392
393
// Execute with custom handling
394
statement.execute { response ->
395
if (response.status.isSuccess()) {
396
response.bodyAsText()
397
} else {
398
"Error: ${response.status}"
399
}
400
}
401
```
402
403
## Types
404
405
### Core Client Types
406
407
```kotlin { .api }
408
interface HttpClientCall {
409
val client: HttpClient
410
val request: HttpRequest
411
val response: HttpResponse
412
val attributes: Attributes
413
414
suspend inline fun <reified T> body(): T
415
suspend inline fun <reified T> bodyNullable(): T?
416
fun save(): SavedHttpCall
417
}
418
419
class SavedHttpCall(
420
override val client: HttpClient,
421
override val request: SavedHttpRequest,
422
override val response: SavedHttpResponse,
423
override val attributes: Attributes
424
) : HttpClientCall
425
426
interface HttpRequest {
427
val call: HttpClientCall
428
val method: HttpMethod
429
val url: Url
430
val attributes: Attributes
431
val headers: Headers
432
val body: OutgoingContent
433
}
434
```
435
436
### Pipeline Types
437
438
```kotlin { .api }
439
class HttpRequestPipeline : Pipeline<Any, HttpRequestBuilder> {
440
companion object {
441
val Before = PipelinePhase("Before")
442
val State = PipelinePhase("State")
443
val Transform = PipelinePhase("Transform")
444
val Render = PipelinePhase("Render")
445
val Send = PipelinePhase("Send")
446
}
447
}
448
449
class HttpResponsePipeline : Pipeline<HttpResponseContainer, HttpClientCall> {
450
companion object {
451
val Receive = PipelinePhase("Receive")
452
val Parse = PipelinePhase("Parse")
453
val Transform = PipelinePhase("Transform")
454
}
455
}
456
457
class HttpSendPipeline : Pipeline<Any, HttpClientCall> {
458
companion object {
459
val Before = PipelinePhase("Before")
460
val State = PipelinePhase("State")
461
val Monitoring = PipelinePhase("Monitoring")
462
val Engine = PipelinePhase("Engine")
463
val Receive = PipelinePhase("Receive")
464
}
465
}
466
467
class HttpReceivePipeline : Pipeline<HttpResponseContainer, HttpClientCall> {
468
companion object {
469
val Before = PipelinePhase("Before")
470
val State = PipelinePhase("State")
471
val After = PipelinePhase("After")
472
}
473
}
474
```