0
# HTTP Client Configuration
1
2
Central client configuration with support for timeouts, proxies, SSL settings, authentication, connection pooling, and protocol selection.
3
4
## Capabilities
5
6
### OkHttpClient
7
8
Main HTTP client for configuring and creating HTTP connections. Intended to be fully configured before sharing and treated as immutable after configuration.
9
10
```java { .api }
11
/**
12
* Configures and creates HTTP connections. Most applications can use a single
13
* OkHttpClient for all of their HTTP requests - benefiting from a shared
14
* response cache, thread pool, connection re-use, etc.
15
*/
16
public class OkHttpClient implements Cloneable {
17
public OkHttpClient();
18
public Call newCall(Request request);
19
public OkHttpClient clone();
20
}
21
```
22
23
**Usage Examples:**
24
25
```java
26
// Create default client
27
OkHttpClient client = new OkHttpClient();
28
29
// Create and execute request
30
Request request = new Request.Builder()
31
.url("https://api.example.com/data")
32
.build();
33
34
Response response = client.newCall(request).execute();
35
```
36
37
### Timeout Configuration
38
39
Configure connection, read, and write timeouts for HTTP requests.
40
41
```java { .api }
42
/**
43
* Sets the default connect timeout for new connections. A value of 0 means no timeout.
44
* @param timeout timeout duration
45
* @param unit time unit for timeout
46
*/
47
public void setConnectTimeout(long timeout, TimeUnit unit);
48
49
/** Default connect timeout (in milliseconds). */
50
public int getConnectTimeout();
51
52
/**
53
* Sets the default read timeout for new connections. A value of 0 means no timeout.
54
* @param timeout timeout duration
55
* @param unit time unit for timeout
56
*/
57
public void setReadTimeout(long timeout, TimeUnit unit);
58
59
/** Default read timeout (in milliseconds). */
60
public int getReadTimeout();
61
62
/**
63
* Sets the default write timeout for new connections. A value of 0 means no timeout.
64
* @param timeout timeout duration
65
* @param unit time unit for timeout
66
*/
67
public void setWriteTimeout(long timeout, TimeUnit unit);
68
69
/** Default write timeout (in milliseconds). */
70
public int getWriteTimeout();
71
```
72
73
**Usage Examples:**
74
75
```java
76
OkHttpClient client = new OkHttpClient();
77
client.setConnectTimeout(30, TimeUnit.SECONDS);
78
client.setReadTimeout(60, TimeUnit.SECONDS);
79
client.setWriteTimeout(60, TimeUnit.SECONDS);
80
```
81
82
### Proxy Configuration
83
84
Configure HTTP proxy settings for client connections.
85
86
```java { .api }
87
/**
88
* Sets the HTTP proxy that will be used by connections created by this
89
* client. This takes precedence over ProxySelector.
90
* @param proxy the proxy to use, or Proxy.NO_PROXY to disable proxy use
91
* @return this client for method chaining
92
*/
93
public OkHttpClient setProxy(Proxy proxy);
94
95
public Proxy getProxy();
96
97
/**
98
* Sets the proxy selection policy to be used if no explicit proxy is specified.
99
* @param proxySelector the proxy selector to use
100
* @return this client for method chaining
101
*/
102
public OkHttpClient setProxySelector(ProxySelector proxySelector);
103
104
public ProxySelector getProxySelector();
105
```
106
107
**Usage Examples:**
108
109
```java
110
// Set explicit proxy
111
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
112
client.setProxy(proxy);
113
114
// Disable proxy
115
client.setProxy(Proxy.NO_PROXY);
116
117
// Use system proxy selector
118
client.setProxySelector(ProxySelector.getDefault());
119
```
120
121
### Cookie Handling
122
123
Configure cookie handling for automatic cookie management.
124
125
```java { .api }
126
/**
127
* Sets the cookie handler to be used to read outgoing cookies and write
128
* incoming cookies.
129
* @param cookieHandler the cookie handler to use
130
* @return this client for method chaining
131
*/
132
public OkHttpClient setCookieHandler(CookieHandler cookieHandler);
133
134
public CookieHandler getCookieHandler();
135
```
136
137
**Usage Examples:**
138
139
```java
140
// Use system cookie manager
141
CookieManager cookieManager = new CookieManager();
142
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
143
client.setCookieHandler(cookieManager);
144
```
145
146
### Cache Configuration
147
148
Configure HTTP response caching with filesystem storage.
149
150
```java { .api }
151
/**
152
* Sets the response cache to be used to read and write cached responses.
153
* @param cache the cache to use
154
* @return this client for method chaining
155
*/
156
public OkHttpClient setCache(Cache cache);
157
158
public Cache getCache();
159
```
160
161
**Usage Examples:**
162
163
```java
164
// Create cache in app's cache directory
165
File cacheDir = new File(context.getCacheDir(), "http-cache");
166
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024); // 10 MB
167
client.setCache(cache);
168
```
169
170
### DNS Configuration
171
172
Configure DNS resolution for hostname lookups.
173
174
```java { .api }
175
/**
176
* Sets the DNS service used to lookup IP addresses for hostnames.
177
* @param dns the DNS service to use
178
* @return this client for method chaining
179
*/
180
public OkHttpClient setDns(Dns dns);
181
182
public Dns getDns();
183
```
184
185
### Socket Factory Configuration
186
187
Configure socket factories for creating network connections.
188
189
```java { .api }
190
/**
191
* Sets the socket factory used to create connections. OkHttp only uses
192
* the parameterless createSocket() method to create unconnected sockets.
193
* @param socketFactory the socket factory to use
194
* @return this client for method chaining
195
*/
196
public OkHttpClient setSocketFactory(SocketFactory socketFactory);
197
198
public SocketFactory getSocketFactory();
199
200
/**
201
* Sets the socket factory used to secure HTTPS connections.
202
* @param sslSocketFactory the SSL socket factory to use
203
* @return this client for method chaining
204
*/
205
public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory);
206
207
public SSLSocketFactory getSslSocketFactory();
208
```
209
210
### SSL/TLS Configuration
211
212
Configure SSL/TLS settings for secure connections.
213
214
```java { .api }
215
/**
216
* Sets the verifier used to confirm that response certificates apply to
217
* requested hostnames for HTTPS connections.
218
* @param hostnameVerifier the hostname verifier to use
219
* @return this client for method chaining
220
*/
221
public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier);
222
223
public HostnameVerifier getHostnameVerifier();
224
225
/**
226
* Sets the certificate pinner that constrains which certificates are trusted.
227
* @param certificatePinner the certificate pinner to use
228
* @return this client for method chaining
229
*/
230
public OkHttpClient setCertificatePinner(CertificatePinner certificatePinner);
231
232
public CertificatePinner getCertificatePinner();
233
```
234
235
### Authentication Configuration
236
237
Configure authentication handling for HTTP challenges.
238
239
```java { .api }
240
/**
241
* Sets the authenticator used to respond to challenges from the remote web
242
* server or proxy server.
243
* @param authenticator the authenticator to use
244
* @return this client for method chaining
245
*/
246
public OkHttpClient setAuthenticator(Authenticator authenticator);
247
248
public Authenticator getAuthenticator();
249
```
250
251
### Connection Pool Configuration
252
253
Configure connection pooling for efficient connection reuse.
254
255
```java { .api }
256
/**
257
* Sets the connection pool used to recycle HTTP and HTTPS connections.
258
* @param connectionPool the connection pool to use
259
* @return this client for method chaining
260
*/
261
public OkHttpClient setConnectionPool(ConnectionPool connectionPool);
262
263
public ConnectionPool getConnectionPool();
264
```
265
266
### Redirect Configuration
267
268
Configure redirect following behavior for HTTP responses.
269
270
```java { .api }
271
/**
272
* Configure this client to follow redirects from HTTPS to HTTP and from HTTP
273
* to HTTPS.
274
* @param followProtocolRedirects whether to follow protocol redirects
275
* @return this client for method chaining
276
*/
277
public OkHttpClient setFollowSslRedirects(boolean followProtocolRedirects);
278
279
public boolean getFollowSslRedirects();
280
281
/**
282
* Configure this client to follow redirects.
283
* @param followRedirects whether to follow redirects
284
*/
285
public void setFollowRedirects(boolean followRedirects);
286
287
public boolean getFollowRedirects();
288
```
289
290
### Retry Configuration
291
292
Configure retry behavior for connection failures.
293
294
```java { .api }
295
/**
296
* Configure this client to retry or not when a connectivity problem is encountered.
297
* @param retryOnConnectionFailure whether to retry on connection failure
298
*/
299
public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure);
300
301
public boolean getRetryOnConnectionFailure();
302
```
303
304
### Protocol Configuration
305
306
Configure supported HTTP protocols for connections.
307
308
```java { .api }
309
/**
310
* Configure the protocols used by this client to communicate with remote
311
* servers. By default this client will prefer the most efficient transport
312
* available, falling back to more ubiquitous protocols.
313
* @param protocols the protocols to use, in order of preference
314
* @return this client for method chaining
315
*/
316
public OkHttpClient setProtocols(List<Protocol> protocols);
317
318
public List<Protocol> getProtocols();
319
320
/**
321
* Sets the connection specifications for socket connections.
322
* @param connectionSpecs the connection specifications to use
323
* @return this client for method chaining
324
*/
325
public OkHttpClient setConnectionSpecs(List<ConnectionSpec> connectionSpecs);
326
327
public List<ConnectionSpec> getConnectionSpecs();
328
```
329
330
### Interceptor Configuration
331
332
Configure interceptors for request and response processing.
333
334
```java { .api }
335
/**
336
* Returns a modifiable list of interceptors that observe the full span of each call.
337
* @return modifiable list of application interceptors
338
*/
339
public List<Interceptor> interceptors();
340
341
/**
342
* Returns a modifiable list of interceptors that observe a single network request and response.
343
* @return modifiable list of network interceptors
344
*/
345
public List<Interceptor> networkInterceptors();
346
```
347
348
**Usage Examples:**
349
350
```java
351
// Add logging interceptor
352
client.interceptors().add(new HttpLoggingInterceptor());
353
354
// Add authentication interceptor
355
client.interceptors().add(new Interceptor() {
356
@Override
357
public Response intercept(Chain chain) throws IOException {
358
Request original = chain.request();
359
Request.Builder requestBuilder = original.newBuilder()
360
.header("Authorization", "Bearer " + getAccessToken());
361
Request request = requestBuilder.build();
362
return chain.proceed(request);
363
}
364
});
365
```
366
367
### Dispatcher Configuration
368
369
Configure the dispatcher for asynchronous request execution.
370
371
```java { .api }
372
/**
373
* Sets the dispatcher used to set policy and execute asynchronous requests.
374
* @param dispatcher the dispatcher to use
375
* @return this client for method chaining
376
*/
377
public OkHttpClient setDispatcher(Dispatcher dispatcher);
378
379
public Dispatcher getDispatcher();
380
```
381
382
### Call Management
383
384
Create and manage HTTP calls.
385
386
```java { .api }
387
/**
388
* Prepares the request to be executed at some point in the future.
389
* @param request the request to prepare
390
* @return a Call ready for execution
391
*/
392
public Call newCall(Request request);
393
394
/**
395
* Cancels all scheduled or in-flight calls tagged with tag. Requests
396
* that are already complete cannot be canceled.
397
* @param tag the tag to match for cancellation
398
* @return this client for method chaining
399
*/
400
public OkHttpClient cancel(Object tag);
401
```
402
403
### Client Cloning
404
405
Create copies of configured clients for further customization.
406
407
```java { .api }
408
/**
409
* Returns a shallow copy of this OkHttpClient.
410
* @return a new OkHttpClient with the same configuration
411
*/
412
@Override
413
public OkHttpClient clone();
414
```
415
416
**Usage Examples:**
417
418
```java
419
// Create base client
420
OkHttpClient baseClient = new OkHttpClient();
421
baseClient.setConnectTimeout(30, TimeUnit.SECONDS);
422
423
// Create specialized client for API calls
424
OkHttpClient apiClient = baseClient.clone();
425
apiClient.interceptors().add(new ApiKeyInterceptor());
426
427
// Create specialized client for file uploads
428
OkHttpClient uploadClient = baseClient.clone();
429
uploadClient.setReadTimeout(300, TimeUnit.SECONDS);
430
uploadClient.setWriteTimeout(300, TimeUnit.SECONDS);
431
```