0
# Request Building
1
2
Comprehensive HTTP request building capabilities including HTTP methods, headers, parameters, body content, and type-safe DSL for constructing HTTP requests.
3
4
## Capabilities
5
6
### HTTP Request Builder
7
8
Core request building functionality with DSL support.
9
10
```kotlin { .api }
11
/**
12
* Builder for constructing HTTP requests
13
*/
14
class HttpRequestBuilder {
15
/** HTTP method (GET, POST, etc.) */
16
var method: HttpMethod = HttpMethod.Get
17
18
/** URL builder for constructing request URLs */
19
val url: URLBuilder = URLBuilder()
20
21
/** Headers builder for request headers */
22
val headers: HeadersBuilder = HeadersBuilder()
23
24
/** Request body content */
25
var body: Any = EmptyContent
26
27
/** Body type information for serialization */
28
var bodyType: TypeInfo? = null
29
30
/** Request execution context */
31
var executionContext: Job = Job()
32
33
/** Request attributes */
34
val attributes: Attributes = Attributes()
35
36
/** Build immutable request data */
37
fun build(): HttpRequestData
38
39
/** Copy from another builder */
40
fun takeFrom(builder: HttpRequestBuilder): HttpRequestBuilder
41
42
/** Copy from another builder with execution context */
43
fun takeFromWithExecutionContext(builder: HttpRequestBuilder): HttpRequestBuilder
44
45
/** Set engine capability */
46
fun <T> setCapability(key: HttpClientEngineCapability<T>, capability: T)
47
48
/** Get engine capability */
49
fun <T> getCapabilityOrNull(key: HttpClientEngineCapability<T>): T?
50
}
51
52
/**
53
* Build an HTTP request using DSL
54
* @param block - Request configuration block
55
*/
56
suspend fun HttpClient.request(
57
block: HttpRequestBuilder.() -> Unit = {}
58
): HttpResponse
59
60
suspend fun HttpClient.request(
61
url: String,
62
block: HttpRequestBuilder.() -> Unit = {}
63
): HttpResponse
64
```
65
66
**Usage Examples:**
67
68
```kotlin
69
import io.ktor.client.request.*
70
import io.ktor.http.*
71
72
val client = HttpClient()
73
74
// Basic request with DSL
75
val response = client.request {
76
method = HttpMethod.Post
77
url("https://api.example.com/users")
78
header("Authorization", "Bearer token123")
79
header("Content-Type", "application/json")
80
setBody("""{"name": "John", "email": "john@example.com"}""")
81
}
82
83
// Request with URL and configuration
84
val getResponse = client.request("https://api.example.com/users") {
85
method = HttpMethod.Get
86
parameter("page", 1)
87
parameter("limit", 10)
88
}
89
```
90
91
### HTTP Method Extensions
92
93
Convenient extension functions for common HTTP methods.
94
95
```kotlin { .api }
96
/**
97
* Perform GET request
98
*/
99
suspend fun HttpClient.get(
100
urlString: String,
101
block: HttpRequestBuilder.() -> Unit = {}
102
): HttpResponse
103
104
suspend fun HttpClient.get(
105
block: HttpRequestBuilder.() -> Unit = {}
106
): HttpResponse
107
108
/**
109
* Perform POST request
110
*/
111
suspend fun HttpClient.post(
112
urlString: String,
113
block: HttpRequestBuilder.() -> Unit = {}
114
): HttpResponse
115
116
suspend fun HttpClient.post(
117
block: HttpRequestBuilder.() -> Unit = {}
118
): HttpResponse
119
120
/**
121
* Perform PUT request
122
*/
123
suspend fun HttpClient.put(
124
urlString: String,
125
block: HttpRequestBuilder.() -> Unit = {}
126
): HttpResponse
127
128
/**
129
* Perform DELETE request
130
*/
131
suspend fun HttpClient.delete(
132
urlString: String,
133
block: HttpRequestBuilder.() -> Unit = {}
134
): HttpResponse
135
136
/**
137
* Perform PATCH request
138
*/
139
suspend fun HttpClient.patch(
140
urlString: String,
141
block: HttpRequestBuilder.() -> Unit = {}
142
): HttpResponse
143
144
/**
145
* Perform HEAD request
146
*/
147
suspend fun HttpClient.head(
148
urlString: String,
149
block: HttpRequestBuilder.() -> Unit = {}
150
): HttpResponse
151
152
/**
153
* Perform OPTIONS request
154
*/
155
suspend fun HttpClient.options(
156
urlString: String,
157
block: HttpRequestBuilder.() -> Unit = {}
158
): HttpResponse
159
```
160
161
**Usage Examples:**
162
163
```kotlin
164
val client = HttpClient()
165
166
// Simple GET request
167
val users = client.get("https://api.example.com/users")
168
169
// POST with body
170
val newUser = client.post("https://api.example.com/users") {
171
contentType(ContentType.Application.Json)
172
setBody("""{"name": "Alice", "email": "alice@example.com"}""")
173
}
174
175
// PUT with parameters
176
val updatedUser = client.put("https://api.example.com/users/123") {
177
parameter("force", true)
178
setBody(userJson)
179
}
180
181
// DELETE request
182
val deleteResponse = client.delete("https://api.example.com/users/123")
183
```
184
185
### URL Building
186
187
Build and manipulate URLs with parameters and path segments.
188
189
```kotlin { .api }
190
/**
191
* URL builder for constructing request URLs
192
*/
193
class URLBuilder {
194
/** Protocol (http, https) */
195
var protocol: URLProtocol = URLProtocol.HTTP
196
197
/** Host name */
198
var host: String = "localhost"
199
200
/** Port number */
201
var port: Int = DEFAULT_PORT
202
203
/** Path segments */
204
val pathSegments: MutableList<String>
205
206
/** Query parameters */
207
val parameters: ParametersBuilder
208
209
/** URL fragment */
210
var fragment: String = ""
211
}
212
213
/**
214
* Set request URL
215
*/
216
fun HttpRequestBuilder.url(urlString: String)
217
fun HttpRequestBuilder.url(url: Url)
218
fun HttpRequestBuilder.url(block: URLBuilder.() -> Unit)
219
```
220
221
**Usage Examples:**
222
223
```kotlin
224
client.get {
225
url {
226
protocol = URLProtocol.HTTPS
227
host = "api.example.com"
228
port = 443
229
path("v1", "users", "123")
230
parameter("include", "profile")
231
parameter("fields", "name,email")
232
fragment = "section1"
233
}
234
}
235
236
// Or using string URL
237
client.get("https://api.example.com/v1/users/123?include=profile&fields=name,email#section1")
238
```
239
240
### Header Management
241
242
Add and manage HTTP headers.
243
244
```kotlin { .api }
245
/**
246
* Set request header
247
*/
248
fun HttpRequestBuilder.header(key: String, value: String)
249
fun HttpRequestBuilder.header(key: String, value: Number)
250
fun HttpRequestBuilder.header(key: String, value: Boolean)
251
252
/**
253
* Append header value (for headers that support multiple values)
254
*/
255
fun HttpRequestBuilder.append(key: String, value: String)
256
257
/**
258
* Set content type header
259
*/
260
fun HttpRequestBuilder.contentType(contentType: ContentType)
261
262
/**
263
* Set accept header
264
*/
265
fun HttpRequestBuilder.accept(contentType: ContentType)
266
267
/**
268
* Set authorization header
269
*/
270
fun HttpRequestBuilder.bearerAuth(token: String)
271
fun HttpRequestBuilder.basicAuth(username: String, password: String)
272
```
273
274
**Usage Examples:**
275
276
```kotlin
277
client.post("https://api.example.com/users") {
278
// Standard headers
279
header("User-Agent", "MyApp/1.0")
280
header("X-Request-ID", UUID.randomUUID().toString())
281
282
// Content type
283
contentType(ContentType.Application.Json)
284
285
// Accept header
286
accept(ContentType.Application.Json)
287
288
// Authentication
289
bearerAuth("your-jwt-token")
290
291
// Multiple values for same header
292
append("Accept-Encoding", "gzip")
293
append("Accept-Encoding", "deflate")
294
}
295
```
296
297
### Parameter Management
298
299
Add URL parameters and form parameters.
300
301
```kotlin { .api }
302
/**
303
* Add URL parameter
304
*/
305
fun HttpRequestBuilder.parameter(key: String, value: Any?)
306
307
/**
308
* Set multiple parameters from map
309
*/
310
fun HttpRequestBuilder.parameters(block: ParametersBuilder.() -> Unit)
311
312
/**
313
* Parameters builder for query string parameters
314
*/
315
class ParametersBuilder {
316
fun append(name: String, value: String)
317
fun appendAll(name: String, values: Iterable<String>)
318
fun set(name: String, value: String)
319
fun remove(name: String)
320
fun clear()
321
}
322
```
323
324
**Usage Examples:**
325
326
```kotlin
327
client.get("https://api.example.com/search") {
328
parameter("q", "kotlin")
329
parameter("limit", 50)
330
parameter("offset", 0)
331
parameter("sort", "created_desc")
332
333
// Multiple parameters at once
334
parameters {
335
append("filter", "published")
336
append("filter", "featured")
337
append("category", "programming")
338
}
339
}
340
```
341
342
### Request Body
343
344
Set request body content with various content types.
345
346
```kotlin { .api }
347
/**
348
* Set request body with type safety
349
*/
350
inline fun <reified T> HttpRequestBuilder.setBody(body: T)
351
352
/**
353
* Set request body with type information
354
*/
355
fun HttpRequestBuilder.setBody(body: Any, bodyType: TypeInfo)
356
357
/**
358
* Set request body (generic)
359
*/
360
fun HttpRequestBuilder.setBody(body: Any)
361
362
/**
363
* Set request body with specific content type
364
*/
365
fun HttpRequestBuilder.setBody(
366
body: Any,
367
contentType: ContentType? = null
368
)
369
370
/**
371
* Base class for outgoing content
372
*/
373
sealed class OutgoingContent {
374
/** Content from byte array */
375
class ByteArrayContent(val bytes: ByteArray) : OutgoingContent()
376
377
/** Content from string */
378
class TextContent(
379
val text: String,
380
val contentType: ContentType
381
) : OutgoingContent()
382
383
/** Content from read channel */
384
class ReadChannelContent(
385
val readFrom: ByteReadChannel
386
) : OutgoingContent()
387
388
/** Content for write channel */
389
class WriteChannelContent(
390
val body: suspend ByteWriteChannel.() -> Unit
391
) : OutgoingContent()
392
393
/** Empty content */
394
object NoContent : OutgoingContent()
395
}
396
```
397
398
**Usage Examples:**
399
400
```kotlin
401
// String body
402
client.post("https://api.example.com/users") {
403
contentType(ContentType.Application.Json)
404
setBody("""{"name": "John", "email": "john@example.com"}""")
405
}
406
407
// Byte array body
408
client.post("https://api.example.com/upload") {
409
contentType(ContentType.Application.OctetStream)
410
setBody(fileBytes)
411
}
412
413
// Object body (requires content negotiation plugin)
414
data class User(val name: String, val email: String)
415
client.post("https://api.example.com/users") {
416
contentType(ContentType.Application.Json)
417
setBody(User("John", "john@example.com"))
418
}
419
420
// Channel content
421
client.post("https://api.example.com/stream") {
422
setBody(ChannelWriterContent { channel ->
423
channel.writeStringUtf8("Hello ")
424
channel.writeStringUtf8("World!")
425
channel.close()
426
})
427
}
428
```
429
430
### Request Utilities
431
432
Utility functions for common request operations.
433
434
```kotlin { .api }
435
/**
436
* Set timeout for specific request
437
*/
438
fun HttpRequestBuilder.timeout(block: HttpTimeoutConfig.() -> Unit)
439
440
/**
441
* Add request attributes
442
*/
443
fun HttpRequestBuilder.attributes(block: Attributes.() -> Unit)
444
445
/**
446
* Set request tag for identification
447
*/
448
fun HttpRequestBuilder.tag(tag: Any)
449
```
450
451
**Usage Examples:**
452
453
```kotlin
454
client.get("https://api.example.com/slow-endpoint") {
455
// Set specific timeout for this request
456
timeout {
457
requestTimeoutMillis = 30000
458
connectTimeoutMillis = 5000
459
}
460
461
// Add custom attributes
462
attributes {
463
put(customAttributeKey, customValue)
464
}
465
466
// Tag request for identification
467
tag("slow-request")
468
}
469
```
470
471
## Types
472
473
```kotlin { .api }
474
// Request types
475
data class HttpRequestData(
476
val url: Url,
477
val method: HttpMethod,
478
val headers: Headers,
479
val body: OutgoingContent,
480
val executionContext: Job,
481
val attributes: Attributes
482
)
483
484
interface HttpRequest : HttpMessage {
485
val call: HttpClientCall
486
val method: HttpMethod
487
val url: Url
488
}
489
490
// URL types
491
enum class URLProtocol {
492
HTTP, HTTPS, WS, WSS, SOCKS
493
}
494
495
// Content types
496
class ContentType private constructor(
497
val contentType: String,
498
val contentSubtype: String,
499
val parameters: List<HeaderValueParam> = emptyList()
500
) {
501
companion object {
502
object Application {
503
val Json = ContentType("application", "json")
504
val Xml = ContentType("application", "xml")
505
val OctetStream = ContentType("application", "octet-stream")
506
val FormUrlEncoded = ContentType("application", "x-www-form-urlencoded")
507
}
508
509
object Text {
510
val Plain = ContentType("text", "plain")
511
val Html = ContentType("text", "html")
512
val CSS = ContentType("text", "css")
513
}
514
}
515
}
516
517
// HTTP methods
518
class HttpMethod(val value: String) {
519
companion object {
520
val Get = HttpMethod("GET")
521
val Post = HttpMethod("POST")
522
val Put = HttpMethod("PUT")
523
val Delete = HttpMethod("DELETE")
524
val Patch = HttpMethod("PATCH")
525
val Head = HttpMethod("HEAD")
526
val Options = HttpMethod("OPTIONS")
527
}
528
}
529
```