0
# Request and Response Handling
1
2
This document covers building HTTP requests and processing responses, including headers, bodies, and metadata handling.
3
4
## Request
5
6
Immutable HTTP request objects with builder pattern for construction.
7
8
```kotlin { .api }
9
class Request private constructor(
10
val url: HttpUrl,
11
val method: String,
12
val headers: Headers,
13
val body: RequestBody?,
14
val cacheUrlOverride: HttpUrl?
15
) {
16
val isHttps: Boolean
17
val cacheControl: CacheControl
18
19
fun header(name: String): String?
20
fun headers(name: String): List<String>
21
fun tag(): Any?
22
fun <T : Any> tag(type: KClass<T>): T?
23
fun <T> tag(type: Class<out T>): T?
24
fun newBuilder(): Builder
25
override fun toString(): String
26
}
27
```
28
29
### Request Builder
30
31
```kotlin { .api }
32
class Request.Builder {
33
fun url(url: HttpUrl): Builder
34
fun url(url: String): Builder
35
fun url(url: URL): Builder
36
fun header(name: String, value: String): Builder
37
fun addHeader(name: String, value: String): Builder
38
fun removeHeader(name: String): Builder
39
fun headers(headers: Headers): Builder
40
fun cacheControl(cacheControl: CacheControl): Builder
41
fun get(): Builder
42
fun head(): Builder
43
fun post(body: RequestBody): Builder
44
fun delete(body: RequestBody? = null): Builder
45
fun put(body: RequestBody): Builder
46
fun patch(body: RequestBody): Builder
47
fun method(method: String, body: RequestBody?): Builder
48
fun tag(tag: Any?): Builder
49
fun <T : Any> tag(type: KClass<T>, tag: T?): Builder
50
fun <T> tag(type: Class<out T>, tag: T?): Builder
51
fun build(): Request
52
}
53
```
54
55
### Request Examples
56
57
#### Basic GET Request
58
59
```kotlin
60
val request = Request.Builder()
61
.url("https://api.example.com/users/123")
62
.header("Accept", "application/json")
63
.header("User-Agent", "MyApp/1.0")
64
.build()
65
```
66
67
#### POST Request with JSON
68
69
```kotlin
70
val json = """{"name": "John Doe", "email": "john@example.com"}"""
71
val body = json.toRequestBody("application/json; charset=utf-8".toMediaType())
72
73
val request = Request.Builder()
74
.url("https://api.example.com/users")
75
.post(body)
76
.header("Content-Type", "application/json")
77
.build()
78
```
79
80
#### Request with Multiple Headers
81
82
```kotlin
83
val request = Request.Builder()
84
.url("https://api.example.com/data")
85
.addHeader("Authorization", "Bearer token123")
86
.addHeader("Accept", "application/json")
87
.addHeader("X-Custom-Header", "value1")
88
.addHeader("X-Custom-Header", "value2") // Multiple values
89
.build()
90
```
91
92
## Response
93
94
Immutable HTTP response objects containing status, headers, and body.
95
96
```kotlin { .api }
97
class Response private constructor() : Closeable {
98
val request: Request
99
val protocol: Protocol
100
val code: Int
101
val message: String
102
val handshake: Handshake?
103
val headers: Headers
104
val body: ResponseBody
105
val networkResponse: Response?
106
val cacheResponse: Response?
107
val priorResponse: Response?
108
val receivedResponseAtMillis: Long
109
val sentRequestAtMillis: Long
110
111
val isSuccessful: Boolean // code in 200..299
112
val isRedirect: Boolean // code in 300..399
113
val cacheControl: CacheControl
114
115
fun header(name: String): String?
116
fun header(name: String, defaultValue: String): String
117
fun headers(name: String): List<String>
118
fun trailers(): Headers
119
fun peekBody(byteCount: Long): ResponseBody
120
fun challenges(): List<Challenge>
121
fun newBuilder(): Builder
122
override fun close()
123
override fun toString(): String
124
}
125
```
126
127
### Response Builder
128
129
```kotlin { .api }
130
class Response.Builder {
131
fun request(request: Request): Builder
132
fun protocol(protocol: Protocol): Builder
133
fun code(code: Int): Builder
134
fun message(message: String): Builder
135
fun handshake(handshake: Handshake?): Builder
136
fun header(name: String, value: String): Builder
137
fun addHeader(name: String, value: String): Builder
138
fun removeHeader(name: String): Builder
139
fun headers(headers: Headers): Builder
140
fun body(body: ResponseBody?): Builder
141
fun networkResponse(networkResponse: Response?): Builder
142
fun cacheResponse(cacheResponse: Response?): Builder
143
fun priorResponse(priorResponse: Response?): Builder
144
fun receivedResponseAtMillis(receivedResponseAtMillis: Long): Builder
145
fun sentRequestAtMillis(sentRequestAtMillis: Long): Builder
146
fun build(): Response
147
}
148
```
149
150
### Response Examples
151
152
#### Processing Response
153
154
```kotlin
155
client.newCall(request).execute().use { response ->
156
println("Status: ${response.code} ${response.message}")
157
println("Success: ${response.isSuccessful}")
158
println("Protocol: ${response.protocol}")
159
160
// Access headers
161
println("Content-Type: ${response.header("Content-Type")}")
162
println("Server: ${response.header("Server", "Unknown")}")
163
164
// Process body
165
if (response.isSuccessful) {
166
val responseBody = response.body?.string()
167
println("Body: $responseBody")
168
}
169
}
170
```
171
172
#### Checking Response Status
173
174
```kotlin
175
val response = client.newCall(request).execute()
176
response.use {
177
when (it.code) {
178
200 -> println("Success: ${it.body?.string()}")
179
404 -> println("Not found")
180
401 -> println("Unauthorized")
181
in 500..599 -> println("Server error: ${it.message}")
182
else -> println("Unexpected response: ${it.code}")
183
}
184
}
185
```
186
187
## Headers
188
189
Immutable HTTP headers collection.
190
191
```kotlin { .api }
192
class Headers private constructor() : Iterable<Pair<String, String>> {
193
val size: Int
194
195
fun name(index: Int): String
196
fun value(index: Int): String
197
operator fun get(name: String): String?
198
fun get(name: String): String?
199
fun getDate(name: String): Date?
200
fun getInstant(name: String): Instant?
201
fun values(name: String): List<String>
202
fun byteCount(): Long
203
fun newBuilder(): Builder
204
fun toMultimap(): Map<String, List<String>>
205
override fun iterator(): Iterator<Pair<String, String>>
206
override fun equals(other: Any?): Boolean
207
override fun hashCode(): Int
208
override fun toString(): String
209
}
210
```
211
212
### Headers Builder
213
214
```kotlin { .api }
215
class Headers.Builder {
216
fun add(name: String, value: String): Builder
217
fun add(name: String, value: Date): Builder
218
fun add(name: String, value: Instant): Builder
219
fun addUnsafeNonAscii(name: String, value: String): Builder
220
fun addAll(headers: Headers): Builder
221
fun set(name: String, value: String): Builder
222
fun set(name: String, value: Date): Builder
223
fun set(name: String, value: Instant): Builder
224
fun removeAll(name: String): Builder
225
operator fun get(name: String): String?
226
fun build(): Headers
227
}
228
```
229
230
### Headers Companion Object
231
232
```kotlin { .api }
233
companion object Headers {
234
fun headersOf(vararg namesAndValues: String): Headers
235
fun headersOf(headers: Map<String, String>): Headers
236
}
237
```
238
239
## RequestBody
240
241
Abstract base class for request bodies.
242
243
```kotlin { .api }
244
abstract class RequestBody {
245
abstract fun contentType(): MediaType?
246
abstract fun contentLength(): Long
247
abstract fun writeTo(sink: BufferedSink)
248
249
open fun isDuplex(): Boolean = false
250
open fun isOneShot(): Boolean = false
251
252
companion object {
253
fun create(content: String, contentType: MediaType? = null): RequestBody
254
fun create(content: ByteString, contentType: MediaType? = null): RequestBody
255
fun create(content: ByteArray, contentType: MediaType? = null, offset: Int = 0, byteCount: Int = content.size): RequestBody
256
fun create(file: File, contentType: MediaType? = null): RequestBody
257
}
258
}
259
```
260
261
### RequestBody Extensions
262
263
```kotlin { .api }
264
fun String.toRequestBody(contentType: MediaType? = null): RequestBody
265
fun ByteString.toRequestBody(contentType: MediaType? = null): RequestBody
266
fun ByteArray.toRequestBody(contentType: MediaType? = null, offset: Int = 0, byteCount: Int = size): RequestBody
267
fun File.asRequestBody(contentType: MediaType? = null): RequestBody
268
```
269
270
## ResponseBody
271
272
Abstract base class for response bodies.
273
274
```kotlin { .api }
275
abstract class ResponseBody : Closeable {
276
abstract fun contentType(): MediaType?
277
abstract fun contentLength(): Long
278
abstract fun source(): BufferedSource
279
280
fun byteStream(): InputStream = source().inputStream()
281
fun bytes(): ByteArray
282
fun byteString(): ByteString
283
fun charStream(): Reader
284
fun string(): String
285
override fun close()
286
287
companion object {
288
fun create(content: String, contentType: MediaType? = null): ResponseBody
289
fun create(content: ByteString, contentType: MediaType? = null): ResponseBody
290
fun create(content: ByteArray, contentType: MediaType? = null): ResponseBody
291
fun create(content: BufferedSource, contentType: MediaType?, contentLength: Long): ResponseBody
292
}
293
}
294
```
295
296
### ResponseBody Extensions
297
298
```kotlin { .api }
299
fun String.toResponseBody(contentType: MediaType? = null): ResponseBody
300
fun ByteString.toResponseBody(contentType: MediaType? = null): ResponseBody
301
fun ByteArray.toResponseBody(contentType: MediaType? = null): ResponseBody
302
fun BufferedSource.asResponseBody(contentType: MediaType? = null, contentLength: Long = -1L): ResponseBody
303
```
304
305
## MediaType
306
307
Represents an RFC 2045 media type.
308
309
```kotlin { .api }
310
class MediaType private constructor() {
311
val type: String
312
val subtype: String
313
val charset: Charset?
314
315
fun charset(): Charset?
316
fun charset(defaultValue: Charset?): Charset?
317
override fun equals(other: Any?): Boolean
318
override fun hashCode(): Int
319
override fun toString(): String
320
321
companion object {
322
fun parse(string: String): MediaType?
323
fun get(string: String): MediaType
324
}
325
}
326
```
327
328
### MediaType Extensions
329
330
```kotlin { .api }
331
fun String.toMediaType(): MediaType
332
fun String.toMediaTypeOrNull(): MediaType?
333
```
334
335
### Common MediaType Usage
336
337
```kotlin
338
// Creating media types
339
val jsonType = "application/json; charset=utf-8".toMediaType()
340
val textType = "text/plain".toMediaType()
341
val formType = "application/x-www-form-urlencoded".toMediaType()
342
343
// Using with request bodies
344
val jsonBody = """{"key": "value"}""".toRequestBody(jsonType)
345
val textBody = "Hello, World!".toRequestBody(textType)
346
```