Square's meticulous HTTP client for Java and Kotlin
npx @tessl/cli install tessl/maven-com-squareup-okhttp3--okhttp@5.1.0OkHttp 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.
com.squareup.okhttp3:okhttp:5.1.0implementation("com.squareup.okhttp3:okhttp:5.1.0")<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>5.1.0</version>
</dependency>import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.RequestBody
import okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.MediaType.Companion.toMediaType
import java.io.IOException
// Create a shared client instance
val client = OkHttpClient()
// GET request
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body?.string())
}
// POST request with JSON
val json = """{"name": "John", "age": 30}"""
val body = json.toRequestBody("application/json; charset=utf-8".toMediaType())
val postRequest = Request.Builder()
.url("https://api.example.com/users")
.post(body)
.build()
client.newCall(postRequest).execute().use { response ->
println("Response: ${response.body?.string()}")
}OkHttp is built around several key components:
Core HTTP client functionality for making requests, handling responses, and managing connections.
class OkHttpClient {
fun newCall(request: Request): Call
fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket
fun newBuilder(): Builder
}
interface Call {
fun execute(): Response
fun enqueue(responseCallback: Callback)
fun cancel()
fun isExecuted(): Boolean
fun isCanceled(): Boolean
}Building HTTP requests and processing responses with headers, bodies, and metadata.
class Request(
val url: HttpUrl,
val method: String,
val headers: Headers,
val body: RequestBody?
) {
class Builder {
fun url(url: String): Builder
fun header(name: String, value: String): Builder
fun get(): Builder
fun post(body: RequestBody): Builder
fun build(): Request
}
}
class Response(
val request: Request,
val protocol: Protocol,
val code: Int,
val message: String,
val headers: Headers,
val body: ResponseBody
) {
val isSuccessful: Boolean
val isRedirect: Boolean
}TLS configuration, certificate management, and authentication handling.
class CertificatePinner {
class Builder {
fun add(hostname: String, vararg pins: String): Builder
fun build(): CertificatePinner
}
}
class ConnectionSpec {
val tlsVersions: List<TlsVersion>?
val cipherSuites: List<CipherSuite>?
companion object {
val MODERN_TLS: ConnectionSpec
val COMPATIBLE_TLS: ConnectionSpec
val CLEARTEXT: ConnectionSpec
}
}HTTP response caching to improve performance and reduce network usage.
class Cache(directory: File, maxSize: Long) {
fun delete()
fun evictAll()
fun size(): Long
fun maxSize(): Long
}
class CacheControl {
val noCache: Boolean
val noStore: Boolean
val maxAgeSeconds: Int
val maxStaleSeconds: Int
companion object {
val FORCE_CACHE: CacheControl
val FORCE_NETWORK: CacheControl
}
}Connection pooling, dispatching, and network configuration.
class ConnectionPool(
maxIdleConnections: Int = 5,
keepAliveDuration: Long = 5,
timeUnit: TimeUnit = TimeUnit.MINUTES
) {
fun idleConnectionCount(): Int
fun connectionCount(): Int
fun evictAll()
}
class Dispatcher {
var maxRequests: Int
var maxRequestsPerHost: Int
val executorService: ExecutorService
}WebSocket protocol support for real-time communication.
interface WebSocket {
fun request(): Request
fun queueSize(): Long
fun send(text: String): Boolean
fun send(bytes: ByteString): Boolean
fun close(code: Int, reason: String?): Boolean
fun cancel()
}
abstract class WebSocketListener {
open fun onOpen(webSocket: WebSocket, response: Response)
open fun onMessage(webSocket: WebSocket, text: String)
open fun onMessage(webSocket: WebSocket, bytes: ByteString)
open fun onClosing(webSocket: WebSocket, code: Int, reason: String)
open fun onClosed(webSocket: WebSocket, code: Int, reason: String)
open fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?)
}Pluggable request and response transformation framework.
interface Interceptor {
fun intercept(chain: Chain): Response
interface Chain {
fun request(): Request
fun proceed(request: Request): Response
fun connection(): Connection?
fun call(): Call
}
}Form data and multipart request body construction.
class FormBody private constructor() : RequestBody() {
class Builder {
fun add(name: String, value: String): Builder
fun addEncoded(name: String, value: String): Builder
fun build(): FormBody
}
}
class MultipartBody private constructor() : RequestBody() {
class Builder {
fun setType(type: MediaType): Builder
fun addPart(headers: Headers?, body: RequestBody): Builder
fun addFormDataPart(name: String, value: String): Builder
fun addFormDataPart(name: String, filename: String?, body: RequestBody): Builder
fun build(): MultipartBody
}
}HTTP cookie storage and handling.
interface CookieJar {
fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>)
fun loadForRequest(url: HttpUrl): List<Cookie>
companion object {
val NO_COOKIES: CookieJar
}
}
data class Cookie(
val name: String,
val value: String,
val expiresAt: Long,
val domain: String,
val path: String,
val secure: Boolean,
val httpOnly: Boolean,
val persistent: Boolean,
val hostOnly: Boolean
)HTTP URL parsing, building, and manipulation.
class HttpUrl private constructor() {
val scheme: String
val host: String
val port: Int
val pathSegments: List<String>
val queryParameterNames: Set<String>
fun queryParameter(name: String): String?
fun queryParameterValues(name: String): List<String>
fun newBuilder(): Builder
class Builder {
fun scheme(scheme: String): Builder
fun host(host: String): Builder
fun port(port: Int): Builder
fun addPathSegment(pathSegment: String): Builder
fun addQueryParameter(name: String, value: String?): Builder
fun build(): HttpUrl
}
companion object {
fun parse(url: String): HttpUrl?
}
}