0
# Server Management
1
2
Core server functionality for creating, starting, stopping, and configuring MockWebServer instances. This provides the foundation for all HTTP testing scenarios.
3
4
## Capabilities
5
6
### MockWebServer Class
7
8
The main server class that provides a scriptable web server for testing HTTP clients.
9
10
```kotlin { .api }
11
/**
12
* A scriptable web server for testing HTTP clients. Extends ExternalResource for JUnit integration.
13
*/
14
class MockWebServer : ExternalResource(), Closeable {
15
/**
16
* Default constructor creates a new MockWebServer instance
17
*/
18
constructor()
19
}
20
```
21
22
### Server Lifecycle
23
24
Control server startup, shutdown, and resource management.
25
26
```kotlin { .api }
27
/**
28
* Start the server on the loopback interface with specified port (0 for random port)
29
* @param port Port number to bind to, or 0 for a random available port
30
*/
31
fun start(port: Int = 0)
32
33
/**
34
* Start the server on specific address and port
35
* @param inetAddress Network interface to bind to
36
* @param port Port number to bind to
37
*/
38
fun start(inetAddress: InetAddress, port: Int)
39
40
/**
41
* Stop the server and release all resources
42
*/
43
fun shutdown()
44
45
/**
46
* Close the server (from Closeable interface)
47
*/
48
fun close()
49
```
50
51
**Usage Examples:**
52
53
```kotlin
54
import okhttp3.mockwebserver.MockWebServer
55
import java.net.InetAddress
56
57
// Start on random port (most common)
58
val server = MockWebServer()
59
server.start()
60
println("Server running on port: ${server.port}")
61
62
// Start on specific port
63
val server2 = MockWebServer()
64
server2.start(8080)
65
66
// Start on specific interface
67
val server3 = MockWebServer()
68
server3.start(InetAddress.getByName("127.0.0.1"), 9000)
69
70
// Always clean up
71
server.shutdown()
72
server2.shutdown()
73
server3.shutdown()
74
```
75
76
### Server Properties
77
78
Access server configuration and connection details.
79
80
```kotlin { .api }
81
/**
82
* Port the server is listening on (read-only)
83
*/
84
val port: Int
85
86
/**
87
* Hostname of the server (read-only)
88
*/
89
val hostName: String
90
91
/**
92
* Number of HTTP requests received by the server
93
*/
94
val requestCount: Int
95
96
/**
97
* Maximum bytes of POST body to keep in memory (default: Long.MAX_VALUE)
98
*/
99
var bodyLimit: Long
100
101
/**
102
* Factory for creating server sockets
103
*/
104
var serverSocketFactory: ServerSocketFactory?
105
```
106
107
### URL Generation
108
109
Generate URLs for client connections.
110
111
```kotlin { .api }
112
/**
113
* Get URL for connecting to server with given path
114
* @param path Path component for the URL (e.g., "/api/users")
115
* @returns HttpUrl instance for client connections
116
*/
117
fun url(path: String): HttpUrl
118
119
/**
120
* Get proxy address for this server
121
* @returns Proxy instance for configuring client proxy settings
122
*/
123
fun toProxyAddress(): Proxy
124
```
125
126
**Usage Examples:**
127
128
```kotlin
129
val server = MockWebServer()
130
server.start()
131
132
// Generate URLs for different endpoints
133
val baseUrl = server.url("/")
134
val apiUrl = server.url("/api/v1/users")
135
val specificUrl = server.url("/path/to/resource?param=value")
136
137
// Use URLs with HTTP client
138
val client = OkHttpClient()
139
val request = Request.Builder()
140
.url(apiUrl)
141
.build()
142
143
val response = client.newCall(request).execute()
144
```
145
146
### Request Queue Management
147
148
Manage queued responses and request counting.
149
150
```kotlin { .api }
151
/**
152
* Queue a response to be served by the default dispatcher
153
* @param response MockResponse to serve for next request
154
*/
155
fun enqueue(response: MockResponse)
156
157
/**
158
* Wait for and return next request (blocking call)
159
* @returns RecordedRequest representing the received HTTP request
160
*/
161
fun takeRequest(): RecordedRequest
162
163
/**
164
* Wait for next request with timeout
165
* @param timeout Maximum time to wait
166
* @param unit Time unit for timeout value
167
* @returns RecordedRequest or null if timeout reached
168
*/
169
fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest?
170
```
171
172
**Usage Examples:**
173
174
```kotlin
175
val server = MockWebServer()
176
177
// Queue multiple responses
178
server.enqueue(MockResponse().setBody("First response"))
179
server.enqueue(MockResponse().setBody("Second response"))
180
server.start()
181
182
// Client makes requests...
183
184
// Verify requests were received
185
val firstRequest = server.takeRequest()
186
val secondRequest = server.takeRequest(5, TimeUnit.SECONDS)
187
188
if (secondRequest != null) {
189
println("Received: ${secondRequest.method} ${secondRequest.path}")
190
}
191
```
192
193
### Dispatcher Configuration
194
195
Configure request handling strategy.
196
197
```kotlin { .api }
198
/**
199
* Dispatcher for handling requests (default: QueueDispatcher)
200
*/
201
var dispatcher: Dispatcher
202
```
203
204
**Usage Examples:**
205
206
```kotlin
207
val server = MockWebServer()
208
209
// Use custom dispatcher for dynamic responses
210
server.dispatcher = object : Dispatcher() {
211
override fun dispatch(request: RecordedRequest): MockResponse {
212
return when (request.path) {
213
"/api/users" -> MockResponse().setBody("User list")
214
"/api/health" -> MockResponse().setBody("OK")
215
else -> MockResponse().setResponseCode(404)
216
}
217
}
218
}
219
220
server.start()
221
```
222
223
### SSL/TLS Configuration
224
225
Configure HTTPS support and client authentication for secure testing scenarios.
226
227
```kotlin { .api }
228
/**
229
* Enable HTTPS support with custom SSL socket factory
230
* @param sslSocketFactory SSL socket factory for creating secure connections
231
* @param tunnelProxy Whether to tunnel connections through proxy
232
*/
233
fun useHttps(sslSocketFactory: SSLSocketFactory, tunnelProxy: Boolean)
234
235
/**
236
* Disable client certificate authentication (default)
237
*/
238
fun noClientAuth()
239
240
/**
241
* Request client certificate authentication (optional)
242
*/
243
fun requestClientAuth()
244
245
/**
246
* Require client certificate authentication (mandatory)
247
*/
248
fun requireClientAuth()
249
```
250
251
**Usage Examples:**
252
253
```kotlin
254
import javax.net.ssl.SSLContext
255
import javax.net.ssl.TrustManager
256
import javax.net.ssl.X509TrustManager
257
258
val server = MockWebServer()
259
260
// Create SSL context for testing
261
val sslContext = SSLContext.getInstance("TLS")
262
val trustManager = object : X509TrustManager {
263
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
264
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
265
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
266
}
267
sslContext.init(null, arrayOf(trustManager), null)
268
269
// Enable HTTPS
270
server.useHttps(sslContext.socketFactory, false)
271
server.start()
272
273
// URLs will use https://
274
val httpsUrl = server.url("/secure/endpoint")
275
```
276
277
### Protocol Negotiation
278
279
Configure HTTP protocol support and negotiation.
280
281
```kotlin { .api }
282
/**
283
* Enable/disable protocol negotiation via ALPN
284
*/
285
var protocolNegotiationEnabled: Boolean
286
287
/**
288
* List of supported HTTP protocols (HTTP/1.1, HTTP/2, etc.)
289
*/
290
var protocols: List<Protocol>
291
```
292
293
**Usage Examples:**
294
295
```kotlin
296
import okhttp3.Protocol
297
298
val server = MockWebServer()
299
300
// Configure protocols
301
server.protocolNegotiationEnabled = true
302
server.protocols = listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)
303
304
server.start()
305
```