CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Square's meticulous HTTP client for Java and Kotlin

Pending
Overview
Eval results
Files

OkHttp

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.

Package Information

  • Package Name: okhttp
  • Package Type: maven
  • Language: Kotlin (Multiplatform)
  • Maven Coordinates: com.squareup.okhttp3:okhttp:5.1.0
  • Installation (Gradle): implementation("com.squareup.okhttp3:okhttp:5.1.0")
  • Installation (Maven):
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>5.1.0</version>
    </dependency>

Core Imports

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.RequestBody
import okhttp3.MediaType.Companion.toMediaType

Basic Usage

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

Architecture

OkHttp is built around several key components:

  • OkHttpClient: Factory for HTTP calls with configurable timeouts, interceptors, and connection pooling
  • Request/Response: Immutable HTTP request and response objects with builders
  • Call: Represents a single HTTP request/response pair, either synchronous or asynchronous
  • Interceptor Framework: Pluggable request/response transformation and monitoring
  • Connection Management: Automatic connection pooling, multiplexing, and keep-alive
  • Security Layer: TLS configuration, certificate pinning, and authentication handling

Capabilities

HTTP Client Operations

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
}

HTTP Client Operations

Request and Response Handling

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
}

Request and Response Handling

Security and TLS

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

Security and TLS

Caching

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

Caching

Connection Management

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
}

Connection Management

WebSocket Support

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

WebSocket Support

Interceptors

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

Interceptors

Form and Multipart Handling

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

Form and Multipart Handling

Cookie Management

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
)

Cookie Management

URL Handling

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

URL Handling

Install with Tessl CLI

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