or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Ktor OkHttp Client Engine

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: io.ktor:ktor-client-okhttp-jvm

7

- **Package Type**: Maven

8

- **Language**: Kotlin (JVM target)

9

- **Installation**: Add `implementation("io.ktor:ktor-client-okhttp-jvm:3.2.0")` to your Gradle build file

10

11

## Core Imports

12

13

```kotlin

14

import io.ktor.client.HttpClient

15

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

16

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

17

```

18

19

## Basic Usage

20

21

```kotlin

22

import io.ktor.client.HttpClient

23

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

24

import io.ktor.client.request.get

25

import io.ktor.client.statement.bodyAsText

26

27

// Create client with OkHttp engine

28

val client = HttpClient(OkHttp)

29

30

// Make a simple request

31

val response = client.get("https://api.example.com/data")

32

val content = response.bodyAsText()

33

34

// Close client when done

35

client.close()

36

```

37

38

## Architecture

39

40

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

41

42

- **Engine Factory**: `OkHttp` object serves as the factory for creating engine instances

43

- **Configuration**: `OkHttpConfig` class provides configuration options and OkHttp client customization

44

- **Engine Implementation**: `OkHttpEngine` handles request execution, WebSocket connections, and SSE streams

45

- **Protocol Support**: HTTP/1.0, HTTP/1.1, HTTP/2, SPDY, and QUIC protocols via OkHttp

46

- **Platform Support**: JVM and Android (minimum API level 21/Android 5.0)

47

48

## Capabilities

49

50

### Engine Factory

51

52

The main entry point for creating OkHttp-based client engines.

53

54

```kotlin { .api }

55

/**

56

* A JVM/Android client engine that uses the OkHttp HTTP client.

57

* This engine supports Android 5.0 and newer.

58

*/

59

public data object OkHttp : HttpClientEngineFactory<OkHttpConfig> {

60

/**

61

* Creates a new OkHttp engine instance with the provided configuration.

62

* @param block Configuration block for OkHttpConfig

63

* @return Configured HttpClientEngine instance

64

*/

65

override fun create(block: OkHttpConfig.() -> Unit): HttpClientEngine

66

67

/**

68

* Compares this object with another for equality.

69

* @param other The object to compare with

70

* @return true if objects are equal, false otherwise

71

*/

72

override fun equals(other: Any?): Boolean

73

74

/**

75

* Returns the hash code for this object.

76

* @return Hash code value

77

*/

78

override fun hashCode(): Int

79

80

/**

81

* Returns string representation of this object.

82

* @return "OkHttp"

83

*/

84

override fun toString(): String

85

}

86

```

87

88

**Usage Example:**

89

90

```kotlin

91

import io.ktor.client.HttpClient

92

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

93

94

// Basic engine usage

95

val client = HttpClient(OkHttp)

96

97

// Engine with configuration

98

val configuredClient = HttpClient(OkHttp) {

99

engine {

100

// OkHttpConfig configuration goes here

101

clientCacheSize = 20

102

}

103

}

104

```

105

106

### Engine Configuration

107

108

Comprehensive configuration options for customizing the OkHttp client behavior.

109

110

```kotlin { .api }

111

/**

112

* A configuration for the OkHttp client engine.

113

*/

114

public class OkHttpConfig : HttpClientEngineConfig() {

115

/**

116

* Allows you to specify a preconfigured OkHttpClient instance.

117

*/

118

public var preconfigured: OkHttpClient?

119

120

/**

121

* Specifies the size of cache that keeps recently used OkHttpClient instances.

122

* Set this property to 0 to disable caching.

123

*/

124

public var clientCacheSize: Int

125

126

/**

127

* Specifies the WebSocket.Factory used to create a WebSocket instance.

128

* Otherwise, OkHttpClient is used directly.

129

*/

130

public var webSocketFactory: WebSocket.Factory?

131

132

/**

133

* Configures OkHttpClient using OkHttpClient.Builder.

134

* @param block Configuration block for OkHttpClient.Builder

135

*/

136

public fun config(block: OkHttpClient.Builder.() -> Unit)

137

138

/**

139

* Adds an Interceptor to the OkHttp client.

140

* @param interceptor Request/response interceptor

141

*/

142

public fun addInterceptor(interceptor: Interceptor)

143

144

/**

145

* Adds a network Interceptor to the OkHttp client.

146

* @param interceptor Network-level interceptor

147

*/

148

public fun addNetworkInterceptor(interceptor: Interceptor)

149

}

150

```

151

152

**Usage Examples:**

153

154

```kotlin

155

import io.ktor.client.HttpClient

156

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

157

import okhttp3.OkHttpClient

158

import okhttp3.logging.HttpLoggingInterceptor

159

import java.util.concurrent.TimeUnit

160

161

// Using preconfigured OkHttpClient

162

val customOkHttpClient = OkHttpClient.Builder()

163

.connectTimeout(30, TimeUnit.SECONDS)

164

.build()

165

166

val client = HttpClient(OkHttp) {

167

engine {

168

preconfigured = customOkHttpClient

169

}

170

}

171

172

// Adding interceptors

173

val clientWithLogging = HttpClient(OkHttp) {

174

engine {

175

addInterceptor(HttpLoggingInterceptor().apply {

176

level = HttpLoggingInterceptor.Level.BODY

177

})

178

179

// Configure client builder directly

180

config {

181

connectTimeout(10, TimeUnit.SECONDS)

182

readTimeout(30, TimeUnit.SECONDS)

183

writeTimeout(30, TimeUnit.SECONDS)

184

}

185

}

186

}

187

188

// Adjusting cache size

189

val cachedClient = HttpClient(OkHttp) {

190

engine {

191

clientCacheSize = 5 // Keep 5 recent client instances

192

}

193

}

194

```

195

196

### Engine Implementation

197

198

The core engine that handles HTTP request execution and various protocol support.

199

200

```kotlin { .api }

201

/**

202

* OkHttp-based HTTP client engine implementation.

203

*/

204

public class OkHttpEngine(override val config: OkHttpConfig) : HttpClientEngineBase("ktor-okhttp") {

205

/**

206

* Set of capabilities supported by this engine.

207

*/

208

override val supportedCapabilities: Set<HttpClientEngineCapability<*>>

209

210

/**

211

* Coroutine context for engine operations.

212

*/

213

override val coroutineContext: CoroutineContext

214

215

/**

216

* Executes an HTTP request and returns the response data.

217

* @param data HTTP request data to execute

218

* @return HTTP response data

219

*/

220

override suspend fun execute(data: HttpRequestData): HttpResponseData

221

222

/**

223

* Closes the engine and cleans up resources.

224

*/

225

override fun close()

226

}

227

```

228

229

### Engine Container

230

231

Container class for engine factory integration.

232

233

```kotlin { .api }

234

/**

235

* Container for the OkHttp engine factory.

236

*/

237

public class OkHttpEngineContainer : HttpClientEngineContainer {

238

/**

239

* The OkHttp engine factory.

240

*/

241

override val factory: HttpClientEngineFactory<*>

242

243

/**

244

* String representation of the container.

245

* @return "OkHttp"

246

*/

247

override fun toString(): String

248

}

249

```

250

251

### Exception Types

252

253

Exception types specific to the OkHttp engine implementation.

254

255

```kotlin { .api }

256

/**

257

* Exception thrown when an unsupported WebSocket frame type is encountered.

258

*/

259

public class UnsupportedFrameTypeException(

260

private val frame: Frame

261

) : IllegalArgumentException("Unsupported frame type: $frame"), CopyableThrowable<UnsupportedFrameTypeException> {

262

/**

263

* Creates a copy of this exception.

264

* @return Copy of the exception

265

*/

266

override fun createCopy(): UnsupportedFrameTypeException

267

}

268

```

269

270

## Supported Capabilities

271

272

The OkHttp engine supports the following Ktor client capabilities:

273

274

- **HttpTimeoutCapability**: Request and connection timeout configuration

275

- **WebSocketCapability**: WebSocket protocol support for real-time communication

276

- **SSECapability**: Server-Sent Events support for streaming data

277

278

**Timeout Configuration Example:**

279

280

```kotlin

281

import io.ktor.client.HttpClient

282

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

283

import io.ktor.client.plugins.HttpTimeout

284

import kotlin.time.Duration.Companion.seconds

285

286

val client = HttpClient(OkHttp) {

287

install(HttpTimeout) {

288

requestTimeoutMillis = 30.seconds.inWholeMilliseconds

289

connectTimeoutMillis = 10.seconds.inWholeMilliseconds

290

socketTimeoutMillis = 30.seconds.inWholeMilliseconds

291

}

292

}

293

```

294

295

**WebSocket Usage Example:**

296

297

```kotlin

298

import io.ktor.client.HttpClient

299

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

300

import io.ktor.client.plugins.websocket.WebSockets

301

import io.ktor.client.plugins.websocket.webSocketSession

302

import io.ktor.websocket.Frame

303

import io.ktor.websocket.readText

304

305

val client = HttpClient(OkHttp) {

306

install(WebSockets)

307

}

308

309

client.webSocketSession("wss://echo.websocket.org") {

310

send(Frame.Text("Hello WebSocket!"))

311

val response = incoming.receive() as Frame.Text

312

println("Received: ${response.readText()}")

313

}

314

```

315

316

**Server-Sent Events Usage Example:**

317

318

```kotlin

319

import io.ktor.client.HttpClient

320

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

321

import io.ktor.client.plugins.sse.SSE

322

import io.ktor.client.plugins.sse.serverSentEvents

323

import kotlinx.coroutines.flow.collect

324

325

val client = HttpClient(OkHttp) {

326

install(SSE)

327

}

328

329

client.serverSentEvents("https://api.example.com/events") {

330

incoming.collect { event ->

331

println("Event: ${event.data}")

332

}

333

}

334

```

335

336

## Platform Support

337

338

- **JVM**: Full support on all JVM versions compatible with Kotlin

339

- **Android**: Minimum Android 5.0 (API level 21)

340

- **Protocols**: HTTP/1.0, HTTP/1.1, HTTP/2, SPDY, QUIC

341

- **Features**: Connection pooling, automatic retry, SSL/TLS support, HTTP/2 server push

342

343

## Dependencies

344

345

This engine requires the following dependencies to be available:

346

347

- `io.ktor:ktor-client-core` - Ktor client core functionality

348

- `com.squareup.okhttp3:okhttp` - OkHttp HTTP client library

349

- `com.squareup.okhttp3:okhttp-sse` - OkHttp Server-Sent Events support

350

- `com.squareup.okio:okio` - Okio I/O library (OkHttp dependency)

351

352

These dependencies are automatically included when you add the `ktor-client-okhttp-jvm` dependency to your project.