A scriptable web server for testing HTTP clients with support for HTTP/1.1, HTTP/2, WebSockets, and SSL/TLS
—
Comprehensive response building capabilities for creating scriptable HTTP responses. MockResponse provides extensive configuration options including status codes, headers, body content, delays, throttling, and connection behavior policies.
Represents a scriptable HTTP response to be served by MockWebServer.
/**
* Represents a scriptable HTTP response. Implements Cloneable for creating response templates.
*/
class MockResponse : Cloneable {
/**
* Default constructor creates a new MockResponse with default settings
*/
constructor()
/**
* Create a copy of the response
* @returns New MockResponse instance with identical configuration
*/
fun clone(): MockResponse
}Configure HTTP response status lines and codes.
/**
* Set the complete HTTP status line (e.g., "HTTP/1.1 200 OK")
* @param status Full status line string
* @returns This MockResponse for method chaining
*/
fun setStatus(status: String): MockResponse
/**
* Set response code with default reason phrase for the code
* @param code HTTP status code (e.g., 200, 404, 500)
* @returns This MockResponse for method chaining
*/
fun setResponseCode(code: Int): MockResponseUsage Examples:
// Set specific status codes
val okResponse = MockResponse().setResponseCode(200)
val notFoundResponse = MockResponse().setResponseCode(404)
val serverErrorResponse = MockResponse().setResponseCode(500)
// Set custom status line
val customResponse = MockResponse().setStatus("HTTP/1.1 418 I'm a teapot")Comprehensive header manipulation including adding, setting, and removing headers.
/**
* Remove all headers
* @returns This MockResponse for method chaining
*/
fun clearHeaders(): MockResponse
/**
* Add header from "name: value" string format
* @param header Header string in "name: value" format
* @returns This MockResponse for method chaining
*/
fun addHeader(header: String): MockResponse
/**
* Add header with separate name and value
* @param name Header name
* @param value Header value (converted to string)
* @returns This MockResponse for method chaining
*/
fun addHeader(name: String, value: Any): MockResponse
/**
* Add header without validation (for testing malformed headers)
* @param name Header name
* @param value Header value
* @returns This MockResponse for method chaining
*/
fun addHeaderLenient(name: String, value: Any): MockResponse
/**
* Replace all headers with given name
* @param name Header name
* @param value New header value
* @returns This MockResponse for method chaining
*/
fun setHeader(name: String, value: Any): MockResponse
/**
* Remove all headers with given name
* @param name Header name to remove
* @returns This MockResponse for method chaining
*/
fun removeHeader(name: String): MockResponse
/**
* Set all headers at once
* @param headers Headers instance containing all headers
* @returns This MockResponse for method chaining
*/
fun setHeaders(headers: Headers): MockResponseUsage Examples:
val response = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.addHeader("X-Custom-Header", "custom-value")
.setHeader("Cache-Control", "no-cache")
// Add multiple cookies
response
.addHeader("Set-Cookie", "session=abc123; Path=/")
.addHeader("Set-Cookie", "theme=dark; Path=/; Max-Age=3600")
// JSON API response headers
val jsonResponse = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Access-Control-Allow-Origin", "*")
.setBody("""{"status": "success"}""")Configure response body content with various encoding options.
/**
* Get response body as Buffer
* @returns Buffer containing response body or null if not set
*/
fun getBody(): Buffer?
/**
* Set response body from Buffer
* @param body Buffer containing response data
* @returns This MockResponse for method chaining
*/
fun setBody(body: Buffer): MockResponse
/**
* Set response body from UTF-8 string
* @param body String content for response body
* @returns This MockResponse for method chaining
*/
fun setBody(body: String): MockResponse
/**
* Set chunked response body from Buffer
* @param body Buffer containing response data
* @param maxChunkSize Maximum size of each chunk in bytes
* @returns This MockResponse for method chaining
*/
fun setChunkedBody(body: Buffer, maxChunkSize: Int): MockResponse
/**
* Set chunked response body from string
* @param body String content for response body
* @param maxChunkSize Maximum size of each chunk in bytes
* @returns This MockResponse for method chaining
*/
fun setChunkedBody(body: String, maxChunkSize: Int): MockResponseUsage Examples:
// Simple text response
val textResponse = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "text/plain")
.setBody("Hello, World!")
// JSON response
val jsonResponse = MockResponse()
.setResponseCode(201)
.addHeader("Content-Type", "application/json")
.setBody("""
{
"id": 123,
"name": "John Doe",
"email": "john@example.com"
}
""".trimIndent())
// Large chunked response
val chunkedResponse = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "text/plain")
.setChunkedBody("A".repeat(10000), 1024) // 10KB in 1KB chunks
// Binary data from Buffer
val buffer = Buffer().writeUtf8("Binary content")
val binaryResponse = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/octet-stream")
.setBody(buffer)Control response timing, delays, and bandwidth throttling.
/**
* Throttle response body transmission
* @param bytesPerPeriod Number of bytes to send per time period
* @param period Duration of each time period
* @param unit Time unit for the period
* @returns This MockResponse for method chaining
*/
fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit): MockResponse
/**
* Get throttle period in specified units
* @param unit Time unit for result
* @returns Throttle period in specified units
*/
fun getThrottlePeriod(unit: TimeUnit): Long
/**
* Set delay before body transmission starts
* @param delay Delay duration
* @param unit Time unit for delay
* @returns This MockResponse for method chaining
*/
fun setBodyDelay(delay: Long, unit: TimeUnit): MockResponse
/**
* Get body delay in specified units
* @param unit Time unit for result
* @returns Body delay in specified units
*/
fun getBodyDelay(unit: TimeUnit): Long
/**
* Set delay before headers are sent
* @param delay Delay duration
* @param unit Time unit for delay
* @returns This MockResponse for method chaining
*/
fun setHeadersDelay(delay: Long, unit: TimeUnit): MockResponse
/**
* Get headers delay in specified units
* @param unit Time unit for result
* @returns Headers delay in specified units
*/
fun getHeadersDelay(unit: TimeUnit): LongUsage Examples:
// Simulate slow network connection
val slowResponse = MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody("""{"data": "large response"}""")
.throttleBody(1024, 1, TimeUnit.SECONDS) // 1KB per second
// Add delays to simulate server processing time
val delayedResponse = MockResponse()
.setResponseCode(200)
.setHeadersDelay(500, TimeUnit.MILLISECONDS) // 500ms before headers
.setBodyDelay(1, TimeUnit.SECONDS) // 1s before body
.setBody("Processed data")
// Simulate very slow server
val verySlowResponse = MockResponse()
.setResponseCode(200)
.setBody("Slow response")
.throttleBody(10, 1, TimeUnit.SECONDS) // Only 10 bytes per secondControl socket behavior and connection lifecycle using SocketPolicy.
/**
* Set socket behavior policy
* @param socketPolicy Policy defining connection behavior
* @returns This MockResponse for method chaining
*/
fun setSocketPolicy(socketPolicy: SocketPolicy): MockResponse
/**
* Socket behavior policy (default: KEEP_OPEN)
*/
var socketPolicy: SocketPolicyUsage Examples:
// Normal HTTP/1.1 behavior (default)
val keepAliveResponse = MockResponse()
.setResponseCode(200)
.setBody("Normal response")
.setSocketPolicy(SocketPolicy.KEEP_OPEN)
// HTTP/1.0 behavior - close after response
val http10Response = MockResponse()
.setResponseCode(200)
.setBody("HTTP/1.0 style")
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)
// Simulate network failures
val failedConnectionResponse = MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)
// Simulate server that reads request but doesn't respond
val hangingResponse = MockResponse()
.setSocketPolicy(SocketPolicy.NO_RESPONSE)
// Simulate SSL handshake failure
val sslFailureResponse = MockResponse()
.setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)Advanced HTTP features including trailers and HTTP/2 specific functionality.
/**
* Set trailers for chunked responses
* @param trailers Headers to send as trailers
* @returns This MockResponse for method chaining
*/
fun setTrailers(trailers: Headers): MockResponse
/**
* Set HTTP/2 error code for stream resets
* @param http2ErrorCode HTTP/2 error code (default: -1 for no error)
* @returns This MockResponse for method chaining
*/
fun setHttp2ErrorCode(http2ErrorCode: Int): MockResponse
/**
* HTTP trailers for chunked responses
*/
var trailers: Headers
/**
* HTTP/2 error code for stream resets (default: -1)
*/
var http2ErrorCode: IntUsage Examples:
// Chunked response with trailers
val trailersResponse = MockResponse()
.setResponseCode(200)
.addHeader("Transfer-Encoding", "chunked")
.setChunkedBody("Response data", 64)
.setTrailers(headersOf("X-Final-Status", "complete"))
// HTTP/2 stream reset
val resetResponse = MockResponse()
.setResponseCode(200)
.setHttp2ErrorCode(8) // CANCEL error codeAdvanced HTTP/2 and WebSocket specific functionality.
/**
* Add informational response (1xx status codes)
* @param informationalResponse MockResponse with 1xx status code
* @returns This MockResponse for method chaining
*/
fun addInformationalResponse(informationalResponse: MockResponse): MockResponse
/**
* Add HTTP/2 server push promise
* @param promise PushPromise containing push information
* @returns This MockResponse for method chaining
*/
fun withPush(promise: PushPromise): MockResponse
/**
* Configure HTTP/2 settings frame
* @param settings HTTP/2 settings to send
* @returns This MockResponse for method chaining
*/
fun withSettings(settings: Settings): MockResponse
/**
* Enable WebSocket upgrade for this response
* @param listener WebSocket listener for handling WebSocket events
* @returns This MockResponse for method chaining
*/
fun withWebSocketUpgrade(listener: WebSocketListener): MockResponseUsage Examples:
import okhttp3.internal.http2.Settings
import okhttp3.WebSocketListener
// HTTP/2 server push
val pushPromise = PushPromise(
"GET",
"/api/user/1/avatar",
headersOf("accept", "image/*"),
MockResponse().setBody("avatar-data")
)
val responseWithPush = MockResponse()
.setResponseCode(200)
.setBody("Main response")
.withPush(pushPromise)
// HTTP/2 settings
val settings = Settings()
settings[Settings.MAX_CONCURRENT_STREAMS] = 100
val responseWithSettings = MockResponse()
.setResponseCode(200)
.withSettings(settings)
// WebSocket upgrade
val wsResponse = MockResponse()
.setResponseCode(101)
.withWebSocketUpgrade(object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
webSocket.send("Hello WebSocket!")
}
})Support for duplex (bidirectional) streaming responses.
/**
* Duplex response body for bidirectional streaming (read-only)
*/
val duplexResponseBody: DuplexResponseBody?
/**
* Whether this response supports duplex streaming (read-only)
*/
val isDuplex: BooleanUsage Examples:
// Check if response supports duplex streaming
val response = MockResponse()
if (response.isDuplex) {
val duplexBody = response.duplexResponseBody
// Handle duplex streaming
}Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp3--mockwebserver