0
# Client Configuration
1
2
Core functionality for creating and configuring HTTP clients with engine selection, plugin installation, and platform-specific configuration options.
3
4
## Capabilities
5
6
### HttpClient Factory Functions
7
8
Create HTTP client instances with different configuration options.
9
10
```kotlin { .api }
11
/**
12
* Creates an asynchronous HttpClient with the specified block configuration.
13
* Note that the client requires an engine for processing network requests.
14
* The HttpClientEngine is selected from the dependencies.
15
*/
16
expect fun HttpClient(
17
block: HttpClientConfig<*>.() -> Unit = {}
18
): HttpClient
19
20
/**
21
* Creates an asynchronous HttpClient with the specified HttpClientEngineFactory and optional block configuration.
22
* Note that a specific platform may require a specific engine for processing requests.
23
*/
24
fun <T : HttpClientEngineConfig> HttpClient(
25
engineFactory: HttpClientEngineFactory<T>,
26
block: HttpClientConfig<T>.() -> Unit = {}
27
): HttpClient
28
29
/**
30
* Creates an asynchronous HttpClient with the specified HttpClientEngine and optional block configuration.
31
*/
32
fun HttpClient(
33
engine: HttpClientEngine,
34
block: HttpClientConfig<*>.() -> Unit
35
): HttpClient
36
```
37
38
**Usage Examples:**
39
40
```kotlin
41
import io.ktor.client.*
42
import io.ktor.client.engine.cio.*
43
44
// Platform-default engine (expect function)
45
val client1 = HttpClient {
46
// Configuration block
47
}
48
49
// Specific engine factory
50
val client2 = HttpClient(CIO) {
51
// Engine-specific configuration
52
}
53
54
// Pre-configured engine instance
55
val engine = CIO.create()
56
val client3 = HttpClient(engine) {
57
// Client configuration
58
}
59
```
60
61
### HttpClient Class
62
63
Main HTTP client class implementing CoroutineScope and Closeable for structured concurrency.
64
65
```kotlin { .api }
66
/**
67
* A multiplatform asynchronous HTTP client, which allows you to make requests and handle responses,
68
* extend its functionality with plugins, such as authentication, JSON serialization, and so on.
69
*/
70
class HttpClient(
71
val engine: HttpClientEngine,
72
private val userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()
73
) : CoroutineScope, Closeable {
74
75
/** A pipeline used for processing all requests sent by this client. */
76
val requestPipeline: HttpRequestPipeline
77
78
/** A pipeline used for processing all responses sent by the server. */
79
val responsePipeline: HttpResponsePipeline
80
81
/** A pipeline used for sending a request. */
82
val sendPipeline: HttpSendPipeline
83
84
/** A pipeline used for receiving a request. */
85
val receivePipeline: HttpReceivePipeline
86
87
/** Typed attributes used as a lightweight container for this client. */
88
val attributes: Attributes
89
90
/** Provides access to the client's engine configuration. */
91
val engineConfig: HttpClientEngineConfig
92
93
/** Provides access to the events of the client's lifecycle. */
94
val monitor: Events
95
96
override val coroutineContext: CoroutineContext
97
98
/**
99
* Checks if the specified capability is supported by this client.
100
*/
101
fun isSupported(capability: HttpClientEngineCapability<*>): Boolean
102
103
/**
104
* Returns a new HttpClient by copying this client's configuration
105
* and additionally configured by the block parameter.
106
*/
107
fun config(block: HttpClientConfig<*>.() -> Unit): HttpClient
108
109
/**
110
* Closes the underlying engine.
111
*/
112
override fun close()
113
}
114
```
115
116
### HttpClientConfig Class
117
118
Configuration builder for HTTP client settings and plugin installation.
119
120
```kotlin { .api }
121
/**
122
* HttpClient configuration builder
123
*/
124
class HttpClientConfig<T : HttpClientEngineConfig> {
125
/** Enable/disable redirect following */
126
var followRedirects: Boolean = true
127
128
/** Use default content transformers */
129
var useDefaultTransformers: Boolean = true
130
131
/** Fail on non-success status codes */
132
var expectSuccess: Boolean = false
133
134
/** Enable development mode features */
135
var developmentMode: Boolean
136
137
/**
138
* Configure engine-specific parameters
139
*/
140
fun engine(block: T.() -> Unit)
141
142
/**
143
* Install a plugin with configuration
144
*/
145
fun <TBuilder : Any, TPlugin : Any> install(
146
plugin: HttpClientPlugin<TBuilder, TPlugin>,
147
configure: TBuilder.() -> Unit = {}
148
)
149
150
/**
151
* Install a custom interceptor with string key
152
*/
153
fun install(key: String, block: HttpClient.() -> Unit)
154
155
/**
156
* Clone this configuration
157
*/
158
fun clone(): HttpClientConfig<T>
159
160
/**
161
* Merge another configuration into this one
162
*/
163
operator fun plusAssign(other: HttpClientConfig<out T>)
164
}
165
```
166
167
**Usage Examples:**
168
169
```kotlin
170
import io.ktor.client.*
171
import io.ktor.client.engine.cio.*
172
import io.ktor.client.plugins.contentnegotiation.*
173
import io.ktor.client.plugins.logging.*
174
175
val client = HttpClient(CIO) {
176
// Basic configuration
177
followRedirects = true
178
expectSuccess = false
179
180
// Engine configuration
181
engine {
182
maxConnectionsCount = 1000
183
requestTimeout = 30_000
184
}
185
186
// Install plugins
187
install(Logging) {
188
logger = Logger.DEFAULT
189
level = LogLevel.INFO
190
}
191
192
install(ContentNegotiation) {
193
json()
194
}
195
196
// Custom interceptor
197
install("CustomMetrics") {
198
// Custom logic
199
}
200
}
201
```
202
203
### Configuration Cloning and Merging
204
205
Advanced configuration management for client reuse and customization.
206
207
```kotlin { .api }
208
/**
209
* Clone a configuration for reuse
210
*/
211
fun HttpClientConfig<T>.clone(): HttpClientConfig<T>
212
213
/**
214
* Merge configurations
215
*/
216
operator fun HttpClientConfig<T>.plusAssign(other: HttpClientConfig<out T>)
217
218
/**
219
* Create a new client with additional configuration
220
*/
221
fun HttpClient.config(block: HttpClientConfig<*>.() -> Unit): HttpClient
222
```
223
224
**Usage Examples:**
225
226
```kotlin
227
// Base configuration
228
val baseConfig = HttpClientConfig<HttpClientEngineConfig>().apply {
229
followRedirects = true
230
install(Logging)
231
}
232
233
// Clone and customize
234
val customConfig = baseConfig.clone().apply {
235
expectSuccess = true
236
install(ContentNegotiation) { json() }
237
}
238
239
// Create client from existing client
240
val baseClient = HttpClient(CIO) {
241
install(Logging)
242
}
243
244
val customClient = baseClient.config {
245
install(ContentNegotiation) { json() }
246
expectSuccess = true
247
}
248
```
249
250
### Client Lifecycle Management
251
252
Proper client lifecycle management with structured concurrency support.
253
254
```kotlin { .api }
255
/**
256
* HttpClient implements Closeable for resource management
257
*/
258
interface Closeable {
259
fun close()
260
}
261
262
/**
263
* HttpClient implements CoroutineScope for structured concurrency
264
*/
265
interface CoroutineScope {
266
val coroutineContext: CoroutineContext
267
}
268
```
269
270
**Usage Examples:**
271
272
```kotlin
273
import kotlinx.coroutines.*
274
275
// Use client in coroutine scope
276
runBlocking {
277
val client = HttpClient(CIO)
278
279
try {
280
// Make requests
281
val response = client.get("https://api.example.com/data")
282
println(response.bodyAsText())
283
} finally {
284
// Always close the client
285
client.close()
286
}
287
}
288
289
// Use client with use function
290
HttpClient(CIO).use { client ->
291
runBlocking {
292
val response = client.get("https://api.example.com/data")
293
println(response.bodyAsText())
294
}
295
}
296
297
// Client inherits coroutine context from engine
298
val client = HttpClient(CIO)
299
launch(client.coroutineContext) {
300
// This coroutine uses the client's context
301
val response = client.get("https://api.example.com/data")
302
}
303
```