Square's meticulous HTTP client for Java and Kotlin
—
This document covers the core HTTP client functionality in OkHttp, including client configuration, making requests, and handling responses.
The main entry point for OkHttp operations. Create one instance and reuse it across your application.
class OkHttpClient {
// Core methods
fun newCall(request: Request): Call
fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket
fun newBuilder(): Builder
// Configuration properties
val dispatcher: Dispatcher
val interceptors: List<Interceptor>
val networkInterceptors: List<Interceptor>
val eventListenerFactory: EventListener.Factory
val retryOnConnectionFailure: Boolean
val fastFallback: Boolean
val authenticator: Authenticator
val followRedirects: Boolean
val followSslRedirects: Boolean
val cookieJar: CookieJar
val cache: Cache?
val dns: Dns
val proxy: Proxy?
val proxySelector: ProxySelector?
val proxyAuthenticator: Authenticator
val socketFactory: SocketFactory
val sslSocketFactory: SSLSocketFactory?
val x509TrustManager: X509TrustManager?
val connectionSpecs: List<ConnectionSpec>
val protocols: List<Protocol>
val hostnameVerifier: HostnameVerifier
val certificatePinner: CertificatePinner
val certificateChainCleaner: CertificateChainCleaner?
val connectionPool: ConnectionPool
val webSocketCloseTimeout: Long
val minWebSocketMessageToCompress: Long
// Timeout properties (in milliseconds)
val callTimeoutMillis: Long
val connectTimeoutMillis: Long
val readTimeoutMillis: Long
val writeTimeoutMillis: Long
val pingIntervalMillis: Long
}Use the Builder to configure client settings:
class OkHttpClient.Builder {
// Timeout configuration
fun callTimeout(timeout: Long, unit: TimeUnit): Builder
fun callTimeout(duration: Duration): Builder
fun connectTimeout(timeout: Long, unit: TimeUnit): Builder
fun connectTimeout(duration: Duration): Builder
fun readTimeout(timeout: Long, unit: TimeUnit): Builder
fun readTimeout(duration: Duration): Builder
fun writeTimeout(timeout: Long, unit: TimeUnit): Builder
fun writeTimeout(duration: Duration): Builder
fun pingInterval(interval: Long, unit: TimeUnit): Builder
fun pingInterval(duration: Duration): Builder
// Network configuration
fun proxy(proxy: Proxy?): Builder
fun proxySelector(proxySelector: ProxySelector): Builder
fun cookieJar(cookieJar: CookieJar): Builder
fun cache(cache: Cache?): Builder
fun dns(dns: Dns): Builder
fun socketFactory(socketFactory: SocketFactory): Builder
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory): Builder
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory, trustManager: X509TrustManager): Builder
fun hostnameVerifier(hostnameVerifier: HostnameVerifier): Builder
fun certificatePinner(certificatePinner: CertificatePinner): Builder
fun authenticator(authenticator: Authenticator): Builder
fun proxyAuthenticator(proxyAuthenticator: Authenticator): Builder
// Connection and request behavior
fun followRedirects(followRedirects: Boolean): Builder
fun followSslRedirects(followSslRedirects: Boolean): Builder
fun retryOnConnectionFailure(retryOnConnectionFailure: Boolean): Builder
fun dispatcher(dispatcher: Dispatcher): Builder
fun protocols(protocols: List<Protocol>): Builder
fun connectionSpecs(connectionSpecs: List<ConnectionSpec>): Builder
fun connectionPool(connectionPool: ConnectionPool): Builder
// Interceptors
fun addInterceptor(interceptor: Interceptor): Builder
fun addNetworkInterceptor(interceptor: Interceptor): Builder
fun interceptors(): MutableList<Interceptor>
fun networkInterceptors(): MutableList<Interceptor>
// Event listening
fun eventListener(listener: EventListener): Builder
fun eventListenerFactory(eventListenerFactory: EventListener.Factory): Builder
fun build(): OkHttpClient
}val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()val client = OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(30))
.readTimeout(Duration.ofSeconds(30))
.followRedirects(true)
.followSslRedirects(false)
.retryOnConnectionFailure(true)
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("User-Agent", "MyApp/1.0")
.build()
chain.proceed(request)
}
.build()Represents a single HTTP request/response exchange.
interface Call : Cloneable {
fun request(): Request
fun execute(): Response
fun enqueue(responseCallback: Callback)
fun cancel()
fun isExecuted(): Boolean
fun isCanceled(): Boolean
fun timeout(): Timeout
override fun clone(): Call
}interface Callback {
fun onFailure(call: Call, e: IOException)
fun onResponse(call: Call, response: Response)
}val request = Request.Builder()
.url("https://api.example.com/data")
.build()
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException("Unexpected code $response")
}
val responseBody = response.body?.string()
println(responseBody)
}
} catch (e: IOException) {
println("Request failed: ${e.message}")
}val request = Request.Builder()
.url("https://api.example.com/data")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("Request failed: ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!it.isSuccessful) {
println("Unexpected code $response")
return
}
val responseBody = it.body?.string()
println(responseBody)
}
}
})Create one client and reuse it for optimal performance:
class ApiClient {
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
fun makeRequest(url: String): Response {
val request = Request.Builder().url(url).build()
return client.newCall(request).execute()
}
}Customize clients for specific needs while sharing connection pools:
val baseClient = OkHttpClient()
// Client with shorter timeout for quick requests
val quickClient = baseClient.newBuilder()
.readTimeout(5, TimeUnit.SECONDS)
.build()
// Client with authentication for API requests
val apiClient = baseClient.newBuilder()
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
chain.proceed(request)
}
.build()Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp3--okhttp