0
# HTTP Client Operations
1
2
This document covers the core HTTP client functionality in OkHttp, including client configuration, making requests, and handling responses.
3
4
## OkHttpClient
5
6
The main entry point for OkHttp operations. Create one instance and reuse it across your application.
7
8
```kotlin { .api }
9
class OkHttpClient {
10
// Core methods
11
fun newCall(request: Request): Call
12
fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket
13
fun newBuilder(): Builder
14
15
// Configuration properties
16
val dispatcher: Dispatcher
17
val interceptors: List<Interceptor>
18
val networkInterceptors: List<Interceptor>
19
val eventListenerFactory: EventListener.Factory
20
val retryOnConnectionFailure: Boolean
21
val fastFallback: Boolean
22
val authenticator: Authenticator
23
val followRedirects: Boolean
24
val followSslRedirects: Boolean
25
val cookieJar: CookieJar
26
val cache: Cache?
27
val dns: Dns
28
val proxy: Proxy?
29
val proxySelector: ProxySelector?
30
val proxyAuthenticator: Authenticator
31
val socketFactory: SocketFactory
32
val sslSocketFactory: SSLSocketFactory?
33
val x509TrustManager: X509TrustManager?
34
val connectionSpecs: List<ConnectionSpec>
35
val protocols: List<Protocol>
36
val hostnameVerifier: HostnameVerifier
37
val certificatePinner: CertificatePinner
38
val certificateChainCleaner: CertificateChainCleaner?
39
val connectionPool: ConnectionPool
40
val webSocketCloseTimeout: Long
41
val minWebSocketMessageToCompress: Long
42
43
// Timeout properties (in milliseconds)
44
val callTimeoutMillis: Long
45
val connectTimeoutMillis: Long
46
val readTimeoutMillis: Long
47
val writeTimeoutMillis: Long
48
val pingIntervalMillis: Long
49
}
50
```
51
52
### Client Configuration
53
54
Use the Builder to configure client settings:
55
56
```kotlin { .api }
57
class OkHttpClient.Builder {
58
// Timeout configuration
59
fun callTimeout(timeout: Long, unit: TimeUnit): Builder
60
fun callTimeout(duration: Duration): Builder
61
fun connectTimeout(timeout: Long, unit: TimeUnit): Builder
62
fun connectTimeout(duration: Duration): Builder
63
fun readTimeout(timeout: Long, unit: TimeUnit): Builder
64
fun readTimeout(duration: Duration): Builder
65
fun writeTimeout(timeout: Long, unit: TimeUnit): Builder
66
fun writeTimeout(duration: Duration): Builder
67
fun pingInterval(interval: Long, unit: TimeUnit): Builder
68
fun pingInterval(duration: Duration): Builder
69
70
// Network configuration
71
fun proxy(proxy: Proxy?): Builder
72
fun proxySelector(proxySelector: ProxySelector): Builder
73
fun cookieJar(cookieJar: CookieJar): Builder
74
fun cache(cache: Cache?): Builder
75
fun dns(dns: Dns): Builder
76
fun socketFactory(socketFactory: SocketFactory): Builder
77
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory): Builder
78
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory, trustManager: X509TrustManager): Builder
79
fun hostnameVerifier(hostnameVerifier: HostnameVerifier): Builder
80
fun certificatePinner(certificatePinner: CertificatePinner): Builder
81
fun authenticator(authenticator: Authenticator): Builder
82
fun proxyAuthenticator(proxyAuthenticator: Authenticator): Builder
83
84
// Connection and request behavior
85
fun followRedirects(followRedirects: Boolean): Builder
86
fun followSslRedirects(followSslRedirects: Boolean): Builder
87
fun retryOnConnectionFailure(retryOnConnectionFailure: Boolean): Builder
88
fun dispatcher(dispatcher: Dispatcher): Builder
89
fun protocols(protocols: List<Protocol>): Builder
90
fun connectionSpecs(connectionSpecs: List<ConnectionSpec>): Builder
91
fun connectionPool(connectionPool: ConnectionPool): Builder
92
93
// Interceptors
94
fun addInterceptor(interceptor: Interceptor): Builder
95
fun addNetworkInterceptor(interceptor: Interceptor): Builder
96
fun interceptors(): MutableList<Interceptor>
97
fun networkInterceptors(): MutableList<Interceptor>
98
99
// Event listening
100
fun eventListener(listener: EventListener): Builder
101
fun eventListenerFactory(eventListenerFactory: EventListener.Factory): Builder
102
103
fun build(): OkHttpClient
104
}
105
```
106
107
### Usage Examples
108
109
#### Basic Client Setup
110
111
```kotlin
112
val client = OkHttpClient.Builder()
113
.connectTimeout(30, TimeUnit.SECONDS)
114
.readTimeout(30, TimeUnit.SECONDS)
115
.writeTimeout(30, TimeUnit.SECONDS)
116
.build()
117
```
118
119
#### Advanced Client Configuration
120
121
```kotlin
122
val client = OkHttpClient.Builder()
123
.connectTimeout(Duration.ofSeconds(30))
124
.readTimeout(Duration.ofSeconds(30))
125
.followRedirects(true)
126
.followSslRedirects(false)
127
.retryOnConnectionFailure(true)
128
.addInterceptor { chain ->
129
val request = chain.request().newBuilder()
130
.addHeader("User-Agent", "MyApp/1.0")
131
.build()
132
chain.proceed(request)
133
}
134
.build()
135
```
136
137
## Call Interface
138
139
Represents a single HTTP request/response exchange.
140
141
```kotlin { .api }
142
interface Call : Cloneable {
143
fun request(): Request
144
fun execute(): Response
145
fun enqueue(responseCallback: Callback)
146
fun cancel()
147
fun isExecuted(): Boolean
148
fun isCanceled(): Boolean
149
fun timeout(): Timeout
150
override fun clone(): Call
151
}
152
```
153
154
### Callback Interface
155
156
```kotlin { .api }
157
interface Callback {
158
fun onFailure(call: Call, e: IOException)
159
fun onResponse(call: Call, response: Response)
160
}
161
```
162
163
### Synchronous Requests
164
165
```kotlin
166
val request = Request.Builder()
167
.url("https://api.example.com/data")
168
.build()
169
170
try {
171
client.newCall(request).execute().use { response ->
172
if (!response.isSuccessful) {
173
throw IOException("Unexpected code $response")
174
}
175
val responseBody = response.body?.string()
176
println(responseBody)
177
}
178
} catch (e: IOException) {
179
println("Request failed: ${e.message}")
180
}
181
```
182
183
### Asynchronous Requests
184
185
```kotlin
186
val request = Request.Builder()
187
.url("https://api.example.com/data")
188
.build()
189
190
client.newCall(request).enqueue(object : Callback {
191
override fun onFailure(call: Call, e: IOException) {
192
println("Request failed: ${e.message}")
193
}
194
195
override fun onResponse(call: Call, response: Response) {
196
response.use {
197
if (!it.isSuccessful) {
198
println("Unexpected code $response")
199
return
200
}
201
val responseBody = it.body?.string()
202
println(responseBody)
203
}
204
}
205
})
206
```
207
208
## Client Patterns
209
210
### Shared Client Instance
211
212
Create one client and reuse it for optimal performance:
213
214
```kotlin
215
class ApiClient {
216
private val client = OkHttpClient.Builder()
217
.connectTimeout(30, TimeUnit.SECONDS)
218
.readTimeout(30, TimeUnit.SECONDS)
219
.build()
220
221
fun makeRequest(url: String): Response {
222
val request = Request.Builder().url(url).build()
223
return client.newCall(request).execute()
224
}
225
}
226
```
227
228
### Per-Request Customization
229
230
Customize clients for specific needs while sharing connection pools:
231
232
```kotlin
233
val baseClient = OkHttpClient()
234
235
// Client with shorter timeout for quick requests
236
val quickClient = baseClient.newBuilder()
237
.readTimeout(5, TimeUnit.SECONDS)
238
.build()
239
240
// Client with authentication for API requests
241
val apiClient = baseClient.newBuilder()
242
.addInterceptor { chain ->
243
val request = chain.request().newBuilder()
244
.addHeader("Authorization", "Bearer $token")
245
.build()
246
chain.proceed(request)
247
}
248
.build()
249
```