or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-io-ktor--ktor-client-okhttp-jvm

A JVM/Android HTTP client engine that uses the OkHttp HTTP client for Ktor framework

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.ktor/ktor-client-okhttp-jvm@3.2.x

To install, run

npx @tessl/cli install tessl/maven-io-ktor--ktor-client-okhttp-jvm@3.2.0

index.mddocs/

Ktor OkHttp Client Engine

Ktor 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.

Package Information

  • Package Name: io.ktor:ktor-client-okhttp-jvm
  • Package Type: Maven
  • Language: Kotlin (JVM target)
  • Installation: Add implementation("io.ktor:ktor-client-okhttp-jvm:3.2.0") to your Gradle build file

Core Imports

import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.engine.okhttp.OkHttpConfig

Basic Usage

import 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()

Architecture

The OkHttp engine integrates with Ktor's client framework through several key components:

  • Engine Factory: OkHttp object serves as the factory for creating engine instances
  • Configuration: OkHttpConfig class provides configuration options and OkHttp client customization
  • Engine Implementation: OkHttpEngine handles request execution, WebSocket connections, and SSE streams
  • Protocol Support: HTTP/1.0, HTTP/1.1, HTTP/2, SPDY, and QUIC protocols via OkHttp
  • Platform Support: JVM and Android (minimum API level 21/Android 5.0)

Capabilities

Engine Factory

The 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
    }
}

Engine Configuration

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
    }
}

Engine Implementation

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()
}

Engine Container

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

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
}

Supported Capabilities

The OkHttp engine supports the following Ktor client capabilities:

  • HttpTimeoutCapability: Request and connection timeout configuration
  • WebSocketCapability: WebSocket protocol support for real-time communication
  • SSECapability: Server-Sent Events support for streaming data

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}")
    }
}

Platform Support

  • JVM: Full support on all JVM versions compatible with Kotlin
  • Android: Minimum Android 5.0 (API level 21)
  • Protocols: HTTP/1.0, HTTP/1.1, HTTP/2, SPDY, QUIC
  • Features: Connection pooling, automatic retry, SSL/TLS support, HTTP/2 server push

Dependencies

This engine requires the following dependencies to be available:

  • io.ktor:ktor-client-core - Ktor client core functionality
  • com.squareup.okhttp3:okhttp - OkHttp HTTP client library
  • com.squareup.okhttp3:okhttp-sse - OkHttp Server-Sent Events support
  • com.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.