or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/maven-com-squareup-okhttp3--okhttp

Square's meticulous HTTP client for Java and Kotlin

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.okhttp3/okhttp@5.1.x

To install, run

npx @tessl/cli install tessl/maven-com-squareup-okhttp3--okhttp@5.1.0

0

# OkHttp

1

2

OkHttp is Square's meticulous HTTP client for Java and Kotlin applications that provides efficient networking capabilities by default. It supports modern HTTP protocols including HTTP/2 and WebSocket connections, implements connection pooling to reduce request latency, provides transparent GZIP compression to minimize bandwidth usage, and includes response caching to avoid redundant network requests.

3

4

## Package Information

5

6

- **Package Name**: okhttp

7

- **Package Type**: maven

8

- **Language**: Kotlin (Multiplatform)

9

- **Maven Coordinates**: `com.squareup.okhttp3:okhttp:5.1.0`

10

- **Installation (Gradle)**: `implementation("com.squareup.okhttp3:okhttp:5.1.0")`

11

- **Installation (Maven)**:

12

```xml

13

<dependency>

14

<groupId>com.squareup.okhttp3</groupId>

15

<artifactId>okhttp</artifactId>

16

<version>5.1.0</version>

17

</dependency>

18

```

19

20

## Core Imports

21

22

```kotlin

23

import okhttp3.OkHttpClient

24

import okhttp3.Request

25

import okhttp3.Response

26

import okhttp3.RequestBody

27

import okhttp3.MediaType.Companion.toMediaType

28

```

29

30

## Basic Usage

31

32

```kotlin

33

import okhttp3.OkHttpClient

34

import okhttp3.Request

35

import okhttp3.RequestBody.Companion.toRequestBody

36

import okhttp3.MediaType.Companion.toMediaType

37

import java.io.IOException

38

39

// Create a shared client instance

40

val client = OkHttpClient()

41

42

// GET request

43

val request = Request.Builder()

44

.url("https://api.example.com/data")

45

.build()

46

47

client.newCall(request).execute().use { response ->

48

if (!response.isSuccessful) throw IOException("Unexpected code $response")

49

println(response.body?.string())

50

}

51

52

// POST request with JSON

53

val json = """{"name": "John", "age": 30}"""

54

val body = json.toRequestBody("application/json; charset=utf-8".toMediaType())

55

56

val postRequest = Request.Builder()

57

.url("https://api.example.com/users")

58

.post(body)

59

.build()

60

61

client.newCall(postRequest).execute().use { response ->

62

println("Response: ${response.body?.string()}")

63

}

64

```

65

66

## Architecture

67

68

OkHttp is built around several key components:

69

70

- **OkHttpClient**: Factory for HTTP calls with configurable timeouts, interceptors, and connection pooling

71

- **Request/Response**: Immutable HTTP request and response objects with builders

72

- **Call**: Represents a single HTTP request/response pair, either synchronous or asynchronous

73

- **Interceptor Framework**: Pluggable request/response transformation and monitoring

74

- **Connection Management**: Automatic connection pooling, multiplexing, and keep-alive

75

- **Security Layer**: TLS configuration, certificate pinning, and authentication handling

76

77

## Capabilities

78

79

### HTTP Client Operations

80

81

Core HTTP client functionality for making requests, handling responses, and managing connections.

82

83

```kotlin { .api }

84

class OkHttpClient {

85

fun newCall(request: Request): Call

86

fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket

87

fun newBuilder(): Builder

88

}

89

90

interface Call {

91

fun execute(): Response

92

fun enqueue(responseCallback: Callback)

93

fun cancel()

94

fun isExecuted(): Boolean

95

fun isCanceled(): Boolean

96

}

97

```

98

99

[HTTP Client Operations](./http-client.md)

100

101

### Request and Response Handling

102

103

Building HTTP requests and processing responses with headers, bodies, and metadata.

104

105

```kotlin { .api }

106

class Request(

107

val url: HttpUrl,

108

val method: String,

109

val headers: Headers,

110

val body: RequestBody?

111

) {

112

class Builder {

113

fun url(url: String): Builder

114

fun header(name: String, value: String): Builder

115

fun get(): Builder

116

fun post(body: RequestBody): Builder

117

fun build(): Request

118

}

119

}

120

121

class Response(

122

val request: Request,

123

val protocol: Protocol,

124

val code: Int,

125

val message: String,

126

val headers: Headers,

127

val body: ResponseBody

128

) {

129

val isSuccessful: Boolean

130

val isRedirect: Boolean

131

}

132

```

133

134

[Request and Response Handling](./requests-responses.md)

135

136

### Security and TLS

137

138

TLS configuration, certificate management, and authentication handling.

139

140

```kotlin { .api }

141

class CertificatePinner {

142

class Builder {

143

fun add(hostname: String, vararg pins: String): Builder

144

fun build(): CertificatePinner

145

}

146

}

147

148

class ConnectionSpec {

149

val tlsVersions: List<TlsVersion>?

150

val cipherSuites: List<CipherSuite>?

151

152

companion object {

153

val MODERN_TLS: ConnectionSpec

154

val COMPATIBLE_TLS: ConnectionSpec

155

val CLEARTEXT: ConnectionSpec

156

}

157

}

158

```

159

160

[Security and TLS](./security.md)

161

162

### Caching

163

164

HTTP response caching to improve performance and reduce network usage.

165

166

```kotlin { .api }

167

class Cache(directory: File, maxSize: Long) {

168

fun delete()

169

fun evictAll()

170

fun size(): Long

171

fun maxSize(): Long

172

}

173

174

class CacheControl {

175

val noCache: Boolean

176

val noStore: Boolean

177

val maxAgeSeconds: Int

178

val maxStaleSeconds: Int

179

180

companion object {

181

val FORCE_CACHE: CacheControl

182

val FORCE_NETWORK: CacheControl

183

}

184

}

185

```

186

187

[Caching](./caching.md)

188

189

### Connection Management

190

191

Connection pooling, dispatching, and network configuration.

192

193

```kotlin { .api }

194

class ConnectionPool(

195

maxIdleConnections: Int = 5,

196

keepAliveDuration: Long = 5,

197

timeUnit: TimeUnit = TimeUnit.MINUTES

198

) {

199

fun idleConnectionCount(): Int

200

fun connectionCount(): Int

201

fun evictAll()

202

}

203

204

class Dispatcher {

205

var maxRequests: Int

206

var maxRequestsPerHost: Int

207

val executorService: ExecutorService

208

}

209

```

210

211

[Connection Management](./networking.md)

212

213

### WebSocket Support

214

215

WebSocket protocol support for real-time communication.

216

217

```kotlin { .api }

218

interface WebSocket {

219

fun request(): Request

220

fun queueSize(): Long

221

fun send(text: String): Boolean

222

fun send(bytes: ByteString): Boolean

223

fun close(code: Int, reason: String?): Boolean

224

fun cancel()

225

}

226

227

abstract class WebSocketListener {

228

open fun onOpen(webSocket: WebSocket, response: Response)

229

open fun onMessage(webSocket: WebSocket, text: String)

230

open fun onMessage(webSocket: WebSocket, bytes: ByteString)

231

open fun onClosing(webSocket: WebSocket, code: Int, reason: String)

232

open fun onClosed(webSocket: WebSocket, code: Int, reason: String)

233

open fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?)

234

}

235

```

236

237

[WebSocket Support](./websockets.md)

238

239

### Interceptors

240

241

Pluggable request and response transformation framework.

242

243

```kotlin { .api }

244

interface Interceptor {

245

fun intercept(chain: Chain): Response

246

247

interface Chain {

248

fun request(): Request

249

fun proceed(request: Request): Response

250

fun connection(): Connection?

251

fun call(): Call

252

}

253

}

254

```

255

256

[Interceptors](./interceptors.md)

257

258

### Form and Multipart Handling

259

260

Form data and multipart request body construction.

261

262

```kotlin { .api }

263

class FormBody private constructor() : RequestBody() {

264

class Builder {

265

fun add(name: String, value: String): Builder

266

fun addEncoded(name: String, value: String): Builder

267

fun build(): FormBody

268

}

269

}

270

271

class MultipartBody private constructor() : RequestBody() {

272

class Builder {

273

fun setType(type: MediaType): Builder

274

fun addPart(headers: Headers?, body: RequestBody): Builder

275

fun addFormDataPart(name: String, value: String): Builder

276

fun addFormDataPart(name: String, filename: String?, body: RequestBody): Builder

277

fun build(): MultipartBody

278

}

279

}

280

```

281

282

[Form and Multipart Handling](./forms-multipart.md)

283

284

### Cookie Management

285

286

HTTP cookie storage and handling.

287

288

```kotlin { .api }

289

interface CookieJar {

290

fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>)

291

fun loadForRequest(url: HttpUrl): List<Cookie>

292

293

companion object {

294

val NO_COOKIES: CookieJar

295

}

296

}

297

298

data class Cookie(

299

val name: String,

300

val value: String,

301

val expiresAt: Long,

302

val domain: String,

303

val path: String,

304

val secure: Boolean,

305

val httpOnly: Boolean,

306

val persistent: Boolean,

307

val hostOnly: Boolean

308

)

309

```

310

311

[Cookie Management](./cookies.md)

312

313

### URL Handling

314

315

HTTP URL parsing, building, and manipulation.

316

317

```kotlin { .api }

318

class HttpUrl private constructor() {

319

val scheme: String

320

val host: String

321

val port: Int

322

val pathSegments: List<String>

323

val queryParameterNames: Set<String>

324

325

fun queryParameter(name: String): String?

326

fun queryParameterValues(name: String): List<String>

327

fun newBuilder(): Builder

328

329

class Builder {

330

fun scheme(scheme: String): Builder

331

fun host(host: String): Builder

332

fun port(port: Int): Builder

333

fun addPathSegment(pathSegment: String): Builder

334

fun addQueryParameter(name: String, value: String?): Builder

335

fun build(): HttpUrl

336

}

337

338

companion object {

339

fun parse(url: String): HttpUrl?

340

}

341

}

342

```

343

344

[URL Handling](./urls.md)