A JVM/Android HTTP client engine that uses the OkHttp HTTP client for Ktor framework
npx @tessl/cli install tessl/maven-io-ktor--ktor-client-okhttp-jvm@3.2.0Ktor OkHttp Client Engine provides a JVM/Android HTTP client engine implementation for the Ktor framework that uses Square's OkHttp library as the underlying HTTP client. It supports Android 5.0 and newer, and offers comprehensive HTTP client functionality including WebSocket support, Server-Sent Events (SSE), custom configuration options, and seamless integration with Ktor's client API.
implementation("io.ktor:ktor-client-okhttp-jvm:3.2.0") to your Gradle build fileimport io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.engine.okhttp.OkHttpConfigimport io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
// Create client with OkHttp engine
val client = HttpClient(OkHttp)
// Make a simple request
val response = client.get("https://api.example.com/data")
val content = response.bodyAsText()
// Close client when done
client.close()The OkHttp engine integrates with Ktor's client framework through several key components:
OkHttp object serves as the factory for creating engine instancesOkHttpConfig class provides configuration options and OkHttp client customizationOkHttpEngine handles request execution, WebSocket connections, and SSE streamsThe main entry point for creating OkHttp-based client engines.
/**
* A JVM/Android client engine that uses the OkHttp HTTP client.
* This engine supports Android 5.0 and newer.
*/
public data object OkHttp : HttpClientEngineFactory<OkHttpConfig> {
/**
* Creates a new OkHttp engine instance with the provided configuration.
* @param block Configuration block for OkHttpConfig
* @return Configured HttpClientEngine instance
*/
override fun create(block: OkHttpConfig.() -> Unit): HttpClientEngine
/**
* Compares this object with another for equality.
* @param other The object to compare with
* @return true if objects are equal, false otherwise
*/
override fun equals(other: Any?): Boolean
/**
* Returns the hash code for this object.
* @return Hash code value
*/
override fun hashCode(): Int
/**
* Returns string representation of this object.
* @return "OkHttp"
*/
override fun toString(): String
}Usage Example:
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
// Basic engine usage
val client = HttpClient(OkHttp)
// Engine with configuration
val configuredClient = HttpClient(OkHttp) {
engine {
// OkHttpConfig configuration goes here
clientCacheSize = 20
}
}Comprehensive configuration options for customizing the OkHttp client behavior.
/**
* A configuration for the OkHttp client engine.
*/
public class OkHttpConfig : HttpClientEngineConfig() {
/**
* Allows you to specify a preconfigured OkHttpClient instance.
*/
public var preconfigured: OkHttpClient?
/**
* Specifies the size of cache that keeps recently used OkHttpClient instances.
* Set this property to 0 to disable caching.
*/
public var clientCacheSize: Int
/**
* Specifies the WebSocket.Factory used to create a WebSocket instance.
* Otherwise, OkHttpClient is used directly.
*/
public var webSocketFactory: WebSocket.Factory?
/**
* Configures OkHttpClient using OkHttpClient.Builder.
* @param block Configuration block for OkHttpClient.Builder
*/
public fun config(block: OkHttpClient.Builder.() -> Unit)
/**
* Adds an Interceptor to the OkHttp client.
* @param interceptor Request/response interceptor
*/
public fun addInterceptor(interceptor: Interceptor)
/**
* Adds a network Interceptor to the OkHttp client.
* @param interceptor Network-level interceptor
*/
public fun addNetworkInterceptor(interceptor: Interceptor)
}Usage Examples:
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit
// Using preconfigured OkHttpClient
val customOkHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.build()
val client = HttpClient(OkHttp) {
engine {
preconfigured = customOkHttpClient
}
}
// Adding interceptors
val clientWithLogging = HttpClient(OkHttp) {
engine {
addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
// Configure client builder directly
config {
connectTimeout(10, TimeUnit.SECONDS)
readTimeout(30, TimeUnit.SECONDS)
writeTimeout(30, TimeUnit.SECONDS)
}
}
}
// Adjusting cache size
val cachedClient = HttpClient(OkHttp) {
engine {
clientCacheSize = 5 // Keep 5 recent client instances
}
}The core engine that handles HTTP request execution and various protocol support.
/**
* OkHttp-based HTTP client engine implementation.
*/
public class OkHttpEngine(override val config: OkHttpConfig) : HttpClientEngineBase("ktor-okhttp") {
/**
* Set of capabilities supported by this engine.
*/
override val supportedCapabilities: Set<HttpClientEngineCapability<*>>
/**
* Coroutine context for engine operations.
*/
override val coroutineContext: CoroutineContext
/**
* Executes an HTTP request and returns the response data.
* @param data HTTP request data to execute
* @return HTTP response data
*/
override suspend fun execute(data: HttpRequestData): HttpResponseData
/**
* Closes the engine and cleans up resources.
*/
override fun close()
}Container class for engine factory integration.
/**
* Container for the OkHttp engine factory.
*/
public class OkHttpEngineContainer : HttpClientEngineContainer {
/**
* The OkHttp engine factory.
*/
override val factory: HttpClientEngineFactory<*>
/**
* String representation of the container.
* @return "OkHttp"
*/
override fun toString(): String
}Exception types specific to the OkHttp engine implementation.
/**
* Exception thrown when an unsupported WebSocket frame type is encountered.
*/
public class UnsupportedFrameTypeException(
private val frame: Frame
) : IllegalArgumentException("Unsupported frame type: $frame"), CopyableThrowable<UnsupportedFrameTypeException> {
/**
* Creates a copy of this exception.
* @return Copy of the exception
*/
override fun createCopy(): UnsupportedFrameTypeException
}The OkHttp engine supports the following Ktor client capabilities:
Timeout Configuration Example:
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpTimeout
import kotlin.time.Duration.Companion.seconds
val client = HttpClient(OkHttp) {
install(HttpTimeout) {
requestTimeoutMillis = 30.seconds.inWholeMilliseconds
connectTimeoutMillis = 10.seconds.inWholeMilliseconds
socketTimeoutMillis = 30.seconds.inWholeMilliseconds
}
}WebSocket Usage Example:
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.plugins.websocket.webSocketSession
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
val client = HttpClient(OkHttp) {
install(WebSockets)
}
client.webSocketSession("wss://echo.websocket.org") {
send(Frame.Text("Hello WebSocket!"))
val response = incoming.receive() as Frame.Text
println("Received: ${response.readText()}")
}Server-Sent Events Usage Example:
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.sse.SSE
import io.ktor.client.plugins.sse.serverSentEvents
import kotlinx.coroutines.flow.collect
val client = HttpClient(OkHttp) {
install(SSE)
}
client.serverSentEvents("https://api.example.com/events") {
incoming.collect { event ->
println("Event: ${event.data}")
}
}This engine requires the following dependencies to be available:
io.ktor:ktor-client-core - Ktor client core functionalitycom.squareup.okhttp3:okhttp - OkHttp HTTP client librarycom.squareup.okhttp3:okhttp-sse - OkHttp Server-Sent Events supportcom.squareup.okio:okio - Okio I/O library (OkHttp dependency)These dependencies are automatically included when you add the ktor-client-okhttp-jvm dependency to your project.