0
# Headers and Parameters
1
2
HTTP header and URL parameter handling with type-safe builders, validation, and comprehensive header name constants.
3
4
## Capabilities
5
6
### Headers Interface
7
8
HTTP headers container with immutable interface and builder support.
9
10
```kotlin { .api }
11
/**
12
* HTTP headers container
13
*/
14
interface Headers : StringValues {
15
16
companion object {
17
/**
18
* Build headers using DSL
19
* @param builder header building function
20
* @return Headers instance
21
*/
22
fun build(builder: HeadersBuilder.() -> Unit): Headers
23
24
/**
25
* Empty headers instance
26
*/
27
val Empty: Headers
28
}
29
}
30
31
/**
32
* Create headers using DSL
33
*/
34
fun headers(builder: HeadersBuilder.() -> Unit): Headers
35
36
/**
37
* Create empty headers
38
*/
39
fun headersOf(): Headers
40
41
/**
42
* Create headers with single header
43
*/
44
fun headersOf(name: String, value: String): Headers
45
46
/**
47
* Create headers with single header and multiple values
48
*/
49
fun headersOf(name: String, values: List<String>): Headers
50
51
/**
52
* Create headers from pairs
53
*/
54
fun headersOf(vararg pairs: Pair<String, String>): Headers
55
```
56
57
### HeadersBuilder
58
59
Mutable headers builder for constructing headers step by step.
60
61
```kotlin { .api }
62
/**
63
* Mutable headers builder
64
*/
65
class HeadersBuilder : StringValuesBuilderImpl {
66
67
/**
68
* Build immutable headers
69
* @return Headers instance
70
*/
71
fun build(): Headers
72
}
73
```
74
75
### HttpHeaders Constants
76
77
Comprehensive HTTP header name constants with validation utilities.
78
79
```kotlin { .api }
80
/**
81
* HTTP header name constants and utilities
82
*/
83
object HttpHeaders {
84
// Request headers
85
val Accept: String
86
val AcceptCharset: String
87
val AcceptEncoding: String
88
val AcceptLanguage: String
89
val Authorization: String
90
val CacheControl: String
91
val Connection: String
92
val ContentEncoding: String
93
val ContentLanguage: String
94
val ContentLength: String
95
val ContentLocation: String
96
val ContentType: String
97
val Cookie: String
98
val Date: String
99
val ETag: String
100
val Expect: String
101
val Expires: String
102
val From: String
103
val Host: String
104
val IfMatch: String
105
val IfModifiedSince: String
106
val IfNoneMatch: String
107
val IfRange: String
108
val IfUnmodifiedSince: String
109
val LastModified: String
110
val Location: String
111
val MaxForwards: String
112
val Origin: String
113
val Pragma: String
114
val ProxyAuthorization: String
115
val Range: String
116
val Referrer: String
117
val RetryAfter: String
118
val Server: String
119
val TE: String
120
val Upgrade: String
121
val UserAgent: String
122
val Vary: String
123
val Via: String
124
val Warning: String
125
126
// Response headers
127
val AcceptRanges: String
128
val Age: String
129
val Allow: String
130
val ContentDisposition: String
131
val ContentRange: String
132
val ProxyAuthenticate: String
133
val SetCookie: String
134
val Trailer: String
135
val TransferEncoding: String
136
val WWWAuthenticate: String
137
138
// CORS headers
139
val AccessControlAllowCredentials: String
140
val AccessControlAllowHeaders: String
141
val AccessControlAllowMethods: String
142
val AccessControlAllowOrigin: String
143
val AccessControlExposeHeaders: String
144
val AccessControlMaxAge: String
145
val AccessControlRequestHeaders: String
146
val AccessControlRequestMethod: String
147
148
// WebDAV headers
149
val DASL: String
150
val DAV: String
151
val Depth: String
152
val Destination: String
153
val If: String
154
val LockToken: String
155
val Overwrite: String
156
val Timeout: String
157
158
// Extended headers
159
val ALPN: String
160
val AuthenticationInfo: String
161
val ContentDisposition: String
162
val Forwarded: String
163
val HTTP2Settings: String
164
val Link: String
165
val MIMEVersion: String
166
val OrderingType: String
167
val Position: String
168
val Prefer: String
169
val PreferenceApplied: String
170
val ProxyAuthenticationInfo: String
171
val PublicKeyPins: String
172
val PublicKeyPinsReportOnly: String
173
val ScheduleReply: String
174
val ScheduleTag: String
175
val SLUG: String
176
val StrictTransportSecurity: String
177
178
// WebSocket headers
179
val SecWebSocketAccept: String
180
val SecWebSocketExtensions: String
181
val SecWebSocketKey: String
182
val SecWebSocketProtocol: String
183
val SecWebSocketVersion: String
184
185
// Non-standard headers
186
val XCorrelationId: String
187
val XForwardedFor: String
188
val XForwardedHost: String
189
val XForwardedPort: String
190
val XForwardedProto: String
191
val XForwardedServer: String
192
val XHttpMethodOverride: String
193
val XRequestId: String
194
val XTotalCount: String
195
196
/**
197
* Validate header name
198
* @param name header name to check
199
* @throws IllegalHeaderNameException if invalid
200
*/
201
fun checkHeaderName(name: String)
202
203
/**
204
* Validate header value
205
* @param value header value to check
206
* @throws IllegalHeaderValueException if invalid
207
*/
208
fun checkHeaderValue(value: String)
209
210
/**
211
* Check if header is considered unsafe
212
* @param name header name
213
* @return true if unsafe
214
*/
215
fun isUnsafe(name: String): Boolean
216
217
/**
218
* Array of unsafe header names
219
*/
220
val unsafeHeaders: Array<String>
221
222
/**
223
* List of unsafe header names
224
*/
225
val unsafeHeadersList: List<String>
226
}
227
```
228
229
### Parameters Interface
230
231
URL parameters container with immutable interface and builder support.
232
233
```kotlin { .api }
234
/**
235
* URL parameters container
236
*/
237
interface Parameters : StringValues {
238
239
companion object {
240
/**
241
* Build parameters using DSL
242
* @param builder parameter building function
243
* @return Parameters instance
244
*/
245
fun build(builder: ParametersBuilder.() -> Unit): Parameters
246
247
/**
248
* Empty parameters instance
249
*/
250
val Empty: Parameters
251
}
252
}
253
254
/**
255
* Parameters builder interface
256
*/
257
interface ParametersBuilder : StringValuesBuilder {
258
/**
259
* Build immutable parameters
260
* @return Parameters instance
261
*/
262
fun build(): Parameters
263
}
264
265
/**
266
* Create parameters using DSL
267
*/
268
fun parameters(builder: ParametersBuilder.() -> Unit): Parameters
269
270
/**
271
* Create empty parameters
272
*/
273
fun parametersOf(): Parameters
274
275
/**
276
* Create parameters with single parameter
277
*/
278
fun parametersOf(name: String, value: String): Parameters
279
280
/**
281
* Create parameters with single parameter and multiple values
282
*/
283
fun parametersOf(name: String, values: List<String>): Parameters
284
285
/**
286
* Create parameters from map
287
*/
288
fun parametersOf(map: Map<String, List<String>>): Parameters
289
290
/**
291
* Create parameters from pairs
292
*/
293
fun parametersOf(vararg pairs: Pair<String, String>): Parameters
294
295
/**
296
* Create parameters builder
297
*/
298
fun ParametersBuilder(initialCapacity: Int = 8): ParametersBuilder
299
300
/**
301
* Combine two parameters instances
302
*/
303
operator fun Parameters.plus(other: Parameters): Parameters
304
```
305
306
### Header Value Parsing
307
308
Utilities for parsing complex header values with parameters.
309
310
```kotlin { .api }
311
/**
312
* Parse header value into structured components
313
* @param text header value text
314
* @return List of HeaderValue instances
315
*/
316
fun parseHeaderValue(text: String): List<HeaderValue>
317
318
/**
319
* Parse header value with parameter control
320
* @param text header value text
321
* @param parametersOnly parse only parameters
322
* @return List of HeaderValue instances
323
*/
324
fun parseHeaderValue(text: String, parametersOnly: Boolean): List<HeaderValue>
325
326
/**
327
* Parse and sort header values by quality
328
* @param text header value text
329
* @return List of HeaderValue instances sorted by quality
330
*/
331
fun parseAndSortHeader(text: String): List<HeaderValue>
332
333
/**
334
* Parse and sort Content-Type header values
335
* @param text Content-Type header text
336
* @return List of HeaderValue instances
337
*/
338
fun parseAndSortContentTypeHeader(text: String): List<HeaderValue>
339
340
/**
341
* Convert parameters to header parameter list
342
* @param parameters parameters to convert
343
* @return List of HeaderValueParam
344
*/
345
fun Iterable<Pair<String, String>>.toHeaderParamsList(): List<HeaderValueParam>
346
```
347
348
### Header Value Types
349
350
Types for representing parsed header values and parameters.
351
352
```kotlin { .api }
353
/**
354
* Parsed header value with quality and parameters
355
*/
356
data class HeaderValue(
357
val value: String,
358
val params: List<HeaderValueParam> = emptyList()
359
) {
360
/**
361
* Quality value from q parameter
362
*/
363
val quality: Double
364
}
365
366
/**
367
* Header parameter with name and value
368
*/
369
data class HeaderValueParam(
370
val name: String,
371
val value: String,
372
val escapeValue: Boolean = false
373
)
374
375
/**
376
* Base class for header values with parameters
377
*/
378
abstract class HeaderValueWithParameters(
379
protected val content: String,
380
val parameters: List<HeaderValueParam> = emptyList()
381
) {
382
/**
383
* Get parameter value by name
384
* @param name parameter name
385
* @return parameter value or null
386
*/
387
fun parameter(name: String): String?
388
389
companion object {
390
/**
391
* Parse header value with custom factory
392
*/
393
fun <T> parse(value: String, factory: (String, List<HeaderValueParam>) -> T): T
394
}
395
}
396
397
/**
398
* Append header value with parameters to builder
399
*/
400
fun StringValuesBuilder.append(name: String, value: HeaderValueWithParameters)
401
402
/**
403
* Escape string if needed for header value
404
*/
405
fun escapeIfNeeded(value: String): String
406
407
/**
408
* Quote string for header value
409
*/
410
fun quote(value: String): String
411
```
412
413
**Usage Examples:**
414
415
```kotlin
416
import io.ktor.http.*
417
418
// Create headers
419
val headers = headers {
420
append(HttpHeaders.ContentType, "application/json")
421
append(HttpHeaders.Authorization, "Bearer token123")
422
append(HttpHeaders.Accept, "application/json, text/plain")
423
}
424
425
// Access header values
426
val contentType = headers[HttpHeaders.ContentType]
427
val acceptValues = headers.getAll(HttpHeaders.Accept)
428
429
// Check for headers
430
if (headers.contains(HttpHeaders.Authorization)) {
431
// Handle authenticated request
432
}
433
434
// Build headers step by step
435
val builder = HeadersBuilder()
436
builder.append(HttpHeaders.UserAgent, "MyApp/1.0")
437
builder.append(HttpHeaders.AcceptEncoding, "gzip, deflate")
438
val builtHeaders = builder.build()
439
440
// Create from predefined values
441
val simpleHeaders = headersOf(
442
HttpHeaders.ContentType to "text/html",
443
HttpHeaders.CacheControl to "no-cache"
444
)
445
446
// Work with parameters
447
val params = parameters {
448
append("page", "1")
449
append("limit", "10")
450
append("sort", listOf("name", "date"))
451
}
452
453
// Access parameter values
454
val page = params["page"] // "1"
455
val sortValues = params.getAll("sort") // ["name", "date"]
456
457
// Create from map
458
val paramMap = mapOf(
459
"filter" to listOf("active", "verified"),
460
"include" to listOf("profile")
461
)
462
val paramsFromMap = parametersOf(paramMap)
463
464
// Combine parameters
465
val combined = params + parametersOf("extra", "value")
466
467
// Parse complex header values
468
val acceptHeader = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
469
val parsed = parseAndSortHeader(acceptHeader)
470
// Sorted by quality value (q parameter)
471
472
// Header validation
473
try {
474
HttpHeaders.checkHeaderName("Valid-Header")
475
HttpHeaders.checkHeaderValue("valid value")
476
} catch (e: IllegalHeaderNameException) {
477
// Handle invalid header name
478
} catch (e: IllegalHeaderValueException) {
479
// Handle invalid header value
480
}
481
482
// Check unsafe headers
483
if (HttpHeaders.isUnsafe("Cookie")) {
484
// Handle unsafe header
485
}
486
```
487
488
## Types
489
490
All types are defined above in their respective capability sections.
491
492
## Exceptions
493
494
```kotlin { .api }
495
/**
496
* Exception thrown for illegal header names
497
*/
498
class IllegalHeaderNameException(
499
val headerName: String,
500
val position: Int
501
) : IllegalArgumentException
502
503
/**
504
* Exception thrown for illegal header values
505
*/
506
class IllegalHeaderValueException(
507
val headerValue: String,
508
val position: Int
509
) : IllegalArgumentException
510
511
/**
512
* Exception thrown for unsafe header usage
513
*/
514
class UnsafeHeaderException(headerName: String) : IllegalArgumentException
515
```