0
# Request Building and Configuration
1
2
Request building DSL for constructing HTTP requests with headers, parameters, body content, and various configuration options using a fluent API.
3
4
## Capabilities
5
6
### HttpRequestBuilder Class
7
8
Main request builder providing a DSL for configuring HTTP requests.
9
10
```kotlin { .api }
11
/**
12
* Builder for constructing HTTP requests with fluent API
13
*/
14
class HttpRequestBuilder {
15
/** HTTP method for the request */
16
var method: HttpMethod
17
18
/** URL builder for constructing request URL */
19
val url: URLBuilder
20
21
/** Headers builder for request headers */
22
val headers: HeadersBuilder
23
24
/** Request body content */
25
var body: Any
26
27
/** Request attributes for storing custom data */
28
val attributes: Attributes
29
30
/** Execution context for the request */
31
var executionContext: Job?
32
33
/** Set single header value */
34
fun header(key: String, value: String)
35
36
/** Configure headers using builder DSL */
37
fun headers(block: HeadersBuilder.() -> Unit)
38
39
/** Add URL parameter */
40
fun parameter(key: String, value: Any?)
41
42
/** Set Accept header */
43
fun accept(contentType: ContentType)
44
45
/** Set Accept-Charset header */
46
fun acceptCharset(charset: Charset)
47
48
/** Set Accept-Encoding header */
49
fun acceptEncoding(encoding: String)
50
51
/** Set Accept-Language header */
52
fun acceptLanguage(language: String)
53
54
/** Set Accept-Ranges header */
55
fun acceptRanges(ranges: String)
56
57
/** Set Cache-Control header */
58
fun cacheControl(cacheControl: CacheControl)
59
60
/** Set Content-Length header */
61
fun contentLength(length: Long)
62
63
/** Set Content-Type header */
64
fun contentType(contentType: ContentType)
65
66
/** Add cookie to request */
67
fun cookie(name: String, value: String, encoding: CookieEncoding = CookieEncoding.URI_ENCODING)
68
69
/** Set Host header */
70
fun host(host: String)
71
72
/** Set port for the request URL */
73
fun port(port: Int)
74
75
/** Set User-Agent header */
76
fun userAgent(agent: String)
77
78
/** Set Basic authentication header */
79
fun basicAuth(username: String, password: String)
80
81
/** Set Bearer token authentication header */
82
fun bearerAuth(token: String)
83
84
/** Configure request timeout */
85
fun timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)
86
87
/** Build the final request data */
88
fun build(): HttpRequestData
89
}
90
```
91
92
**Usage Examples:**
93
94
```kotlin
95
import io.ktor.client.*
96
import io.ktor.client.request.*
97
import io.ktor.http.*
98
99
val client = HttpClient()
100
101
// Basic request building
102
val response = client.request {
103
method = HttpMethod.Post
104
url("https://api.example.com/users")
105
106
headers {
107
append("Content-Type", "application/json")
108
append("Accept", "application/json")
109
}
110
111
setBody("""{"name": "John", "email": "john@example.com"}""")
112
}
113
114
// Advanced request configuration
115
val advancedResponse = client.request {
116
method = HttpMethod.Get
117
118
url {
119
protocol = URLProtocol.HTTPS
120
host = "api.example.com"
121
path("v1", "users")
122
parameter("page", 1)
123
parameter("limit", 10)
124
parameter("sort", "name")
125
}
126
127
headers {
128
append("Authorization", "Bearer $token")
129
append("Accept", "application/vnd.api+json")
130
append("User-Agent", "MyApp/1.0")
131
}
132
133
timeout {
134
requestTimeoutMillis = 30000
135
connectTimeoutMillis = 10000
136
}
137
}
138
```
139
140
### URL Configuration
141
142
URL building capabilities for constructing request URLs with parameters and path segments.
143
144
```kotlin { .api }
145
/**
146
* URL builder for constructing request URLs
147
*/
148
class URLBuilder {
149
/** URL protocol (HTTP, HTTPS) */
150
var protocol: URLProtocol
151
152
/** Host name */
153
var host: String
154
155
/** Port number */
156
var port: Int
157
158
/** URL path segments */
159
val pathSegments: MutableList<String>
160
161
/** URL parameters */
162
val parameters: ParametersBuilder
163
164
/** URL fragment */
165
var fragment: String
166
167
/** Username for authentication */
168
var user: String?
169
170
/** Password for authentication */
171
var password: String?
172
173
/** Append path segments */
174
fun path(vararg components: String)
175
176
/** Set or append path segments */
177
fun appendPath(path: String)
178
179
/** Add URL parameter */
180
fun parameter(name: String, value: Any?)
181
182
/** Build final URL */
183
fun build(): Url
184
}
185
186
/**
187
* Configure URL in request builder
188
* @param block URL configuration block
189
*/
190
fun HttpRequestBuilder.url(block: URLBuilder.() -> Unit)
191
192
/**
193
* Set URL from string
194
* @param urlString URL string to parse
195
*/
196
fun HttpRequestBuilder.url(urlString: String)
197
```
198
199
**Usage Examples:**
200
201
```kotlin
202
import io.ktor.client.*
203
import io.ktor.client.request.*
204
import io.ktor.http.*
205
206
val client = HttpClient()
207
208
// URL building with DSL
209
val response = client.get {
210
url {
211
protocol = URLProtocol.HTTPS
212
host = "api.github.com"
213
path("repos", "ktorio", "ktor", "issues")
214
parameter("state", "open")
215
parameter("labels", "bug")
216
parameter("per_page", 50)
217
}
218
}
219
220
// URL building with string base
221
val response2 = client.post("https://api.example.com/data") {
222
url {
223
parameter("format", "json")
224
parameter("timestamp", System.currentTimeMillis())
225
}
226
227
setBody(requestData)
228
}
229
230
// Complex URL construction
231
val response3 = client.request {
232
method = HttpMethod.Get
233
url {
234
protocol = URLProtocol.HTTPS
235
host = "api.example.com"
236
port = 443
237
path("v2", "search", "repositories")
238
parameter("q", "language:kotlin")
239
parameter("sort", "stars")
240
parameter("order", "desc")
241
fragment = "results"
242
}
243
}
244
```
245
246
### Header Configuration
247
248
Header management for setting and configuring HTTP request headers.
249
250
```kotlin { .api }
251
/**
252
* Headers builder for managing request headers
253
*/
254
class HeadersBuilder : StringValuesBuilder {
255
/** Append header value */
256
fun append(name: String, value: String)
257
258
/** Set header value (replace existing) */
259
fun set(name: String, value: String)
260
261
/** Remove header */
262
fun remove(name: String)
263
264
/** Append all headers from another headers collection */
265
fun appendAll(headers: Headers)
266
267
/** Check if header exists */
268
fun contains(name: String): Boolean
269
270
/** Get header values */
271
fun getAll(name: String): List<String>?
272
273
/** Build final headers */
274
fun build(): Headers
275
}
276
277
/**
278
* Convenient header setting functions in HttpRequestBuilder
279
*/
280
fun HttpRequestBuilder.header(key: String, value: String)
281
fun HttpRequestBuilder.headers(block: HeadersBuilder.() -> Unit)
282
fun HttpRequestBuilder.accept(contentType: ContentType)
283
fun HttpRequestBuilder.acceptCharset(charset: Charset)
284
fun HttpRequestBuilder.acceptEncoding(encoding: String)
285
fun HttpRequestBuilder.acceptLanguage(language: String)
286
fun HttpRequestBuilder.acceptRanges(ranges: String)
287
fun HttpRequestBuilder.cacheControl(cacheControl: CacheControl)
288
fun HttpRequestBuilder.contentLength(length: Long)
289
fun HttpRequestBuilder.contentType(contentType: ContentType)
290
fun HttpRequestBuilder.userAgent(agent: String)
291
```
292
293
**Usage Examples:**
294
295
```kotlin
296
import io.ktor.client.*
297
import io.ktor.client.request.*
298
import io.ktor.http.*
299
300
val client = HttpClient()
301
302
// Basic header configuration
303
val response = client.post("https://api.example.com/data") {
304
headers {
305
append("Content-Type", "application/json")
306
append("Accept", "application/json")
307
append("Authorization", "Bearer $token")
308
append("X-Client-Version", "1.0.0")
309
}
310
311
setBody(jsonData)
312
}
313
314
// Convenient header functions
315
val response2 = client.get("https://api.example.com/data") {
316
accept(ContentType.Application.Json)
317
contentType(ContentType.Application.Json)
318
userAgent("MyApp/1.0 (Platform/Version)")
319
acceptEncoding("gzip, deflate")
320
acceptLanguage("en-US,en;q=0.9")
321
322
header("X-API-Key", apiKey)
323
header("X-Request-ID", requestId)
324
}
325
326
// Conditional headers
327
val response3 = client.request {
328
method = HttpMethod.Get
329
url("https://api.example.com/resource")
330
331
headers {
332
append("Accept", "application/json")
333
334
if (authToken != null) {
335
append("Authorization", "Bearer $authToken")
336
}
337
338
if (etag != null) {
339
append("If-None-Match", etag)
340
}
341
342
append("Cache-Control", "max-age=300")
343
}
344
}
345
```
346
347
### Authentication Configuration
348
349
Authentication helpers for setting various authentication headers.
350
351
```kotlin { .api }
352
/**
353
* Set Basic authentication header
354
* @param username Username for authentication
355
* @param password Password for authentication
356
*/
357
fun HttpRequestBuilder.basicAuth(username: String, password: String)
358
359
/**
360
* Set Bearer token authentication header
361
* @param token Bearer token value
362
*/
363
fun HttpRequestBuilder.bearerAuth(token: String)
364
365
/**
366
* Add cookie to request
367
* @param name Cookie name
368
* @param value Cookie value
369
* @param encoding Cookie encoding method
370
*/
371
fun HttpRequestBuilder.cookie(
372
name: String,
373
value: String,
374
encoding: CookieEncoding = CookieEncoding.URI_ENCODING
375
)
376
```
377
378
**Usage Examples:**
379
380
```kotlin
381
import io.ktor.client.*
382
import io.ktor.client.request.*
383
384
val client = HttpClient()
385
386
// Basic authentication
387
val basicResponse = client.get("https://api.example.com/protected") {
388
basicAuth("username", "password")
389
}
390
391
// Bearer token authentication
392
val bearerResponse = client.get("https://api.example.com/protected") {
393
bearerAuth("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
394
}
395
396
// Cookie authentication
397
val cookieResponse = client.get("https://example.com/dashboard") {
398
cookie("session_id", "abc123def456")
399
cookie("preferences", "theme=dark&lang=en")
400
}
401
402
// Custom authentication header
403
val customResponse = client.get("https://api.example.com/data") {
404
header("X-API-Key", "your-api-key-here")
405
header("X-Auth-Token", "custom-token-format")
406
}
407
```
408
409
### Request Body Configuration
410
411
Request body setting for various content types and data formats.
412
413
```kotlin { .api }
414
/**
415
* Set request body content
416
* @param body Body content (String, ByteArray, OutgoingContent, etc.)
417
*/
418
fun HttpRequestBuilder.setBody(body: Any?)
419
420
/** Request body property */
421
var HttpRequestBuilder.body: Any
422
```
423
424
**Usage Examples:**
425
426
```kotlin
427
import io.ktor.client.*
428
import io.ktor.client.request.*
429
import io.ktor.http.*
430
import io.ktor.utils.io.*
431
432
val client = HttpClient()
433
434
// JSON body
435
val jsonResponse = client.post("https://api.example.com/users") {
436
contentType(ContentType.Application.Json)
437
setBody("""{"name": "John", "email": "john@example.com"}""")
438
}
439
440
// Text body
441
val textResponse = client.post("https://api.example.com/notes") {
442
contentType(ContentType.Text.Plain)
443
setBody("This is a plain text note")
444
}
445
446
// Binary body
447
val binaryData = byteArrayOf(0x89, 0x50, 0x4E, 0x47) // PNG header example
448
val binaryResponse = client.post("https://api.example.com/upload") {
449
contentType(ContentType.Application.OctetStream)
450
setBody(binaryData)
451
}
452
453
// Custom content
454
val customContent = object : OutgoingContent.WriteChannelContent() {
455
override val contentType = ContentType.Application.Json
456
override val contentLength = jsonData.length.toLong()
457
458
override suspend fun writeTo(channel: ByteWriteChannel) {
459
channel.writeStringUtf8(jsonData)
460
}
461
}
462
463
val customResponse = client.post("https://api.example.com/custom") {
464
setBody(customContent)
465
}
466
```
467
468
### Timeout Configuration
469
470
Request timeout configuration for controlling request timing behavior.
471
472
```kotlin { .api }
473
/**
474
* Configure request timeout settings
475
* @param block Timeout configuration block
476
*/
477
fun HttpRequestBuilder.timeout(block: HttpTimeoutCapabilityConfiguration.() -> Unit)
478
479
/**
480
* Timeout configuration options
481
*/
482
class HttpTimeoutCapabilityConfiguration {
483
/** Request timeout in milliseconds */
484
var requestTimeoutMillis: Long?
485
486
/** Connection timeout in milliseconds */
487
var connectTimeoutMillis: Long?
488
489
/** Socket timeout in milliseconds */
490
var socketTimeoutMillis: Long?
491
}
492
```
493
494
**Usage Examples:**
495
496
```kotlin
497
import io.ktor.client.*
498
import io.ktor.client.request.*
499
500
val client = HttpClient()
501
502
// Basic timeout configuration
503
val response = client.get("https://slow-api.example.com/data") {
504
timeout {
505
requestTimeoutMillis = 30000 // 30 seconds
506
connectTimeoutMillis = 10000 // 10 seconds
507
socketTimeoutMillis = 20000 // 20 seconds
508
}
509
}
510
511
// Different timeouts for different operations
512
val uploadResponse = client.post("https://api.example.com/upload") {
513
setBody(largeFileData)
514
515
timeout {
516
requestTimeoutMillis = 300000 // 5 minutes for uploads
517
connectTimeoutMillis = 15000 // 15 seconds to connect
518
}
519
}
520
521
// No timeout (infinite)
522
val longRunningResponse = client.get("https://api.example.com/long-process") {
523
timeout {
524
requestTimeoutMillis = null // No request timeout
525
}
526
}
527
```
528
529
## Types
530
531
### Request Builder Types
532
533
```kotlin { .api }
534
class HttpRequestData(
535
val url: Url,
536
val method: HttpMethod,
537
val headers: Headers,
538
val body: OutgoingContent,
539
val executionContext: Job,
540
val attributes: Attributes
541
)
542
543
enum class CookieEncoding {
544
URI_ENCODING,
545
DQUOTES,
546
RAW
547
}
548
549
class CacheControl(
550
val value: String
551
) {
552
companion object {
553
val NoCache = CacheControl("no-cache")
554
val NoStore = CacheControl("no-store")
555
val MaxAge = { seconds: Int -> CacheControl("max-age=$seconds") }
556
}
557
}
558
```
559
560
### Parameter Types
561
562
```kotlin { .api }
563
class ParametersBuilder(size: Int = 8) : StringValuesBuilder {
564
fun append(name: String, value: String)
565
fun appendAll(stringValues: StringValues)
566
fun appendAll(name: String, values: Iterable<String>)
567
fun appendMissing(stringValues: StringValues)
568
fun appendMissing(name: String, values: Iterable<String>)
569
fun set(name: String, value: String)
570
fun setAll(stringValues: StringValues)
571
fun setAll(name: String, values: Iterable<String>)
572
fun remove(name: String): Boolean
573
fun removeKeysWithNoEntries()
574
fun clear()
575
fun build(): Parameters
576
}
577
578
interface Parameters : StringValues {
579
companion object {
580
val Empty: Parameters
581
}
582
}
583
```