/
OkHttpClient.kt
1402 lines (1265 loc) · 52 KB
/
OkHttpClient.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import android.annotation.SuppressLint
import java.net.Proxy
import java.net.ProxySelector
import java.net.Socket
import java.time.Duration
import java.util.Collections
import java.util.Random
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
import javax.net.SocketFactory
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager
import kotlin.time.Duration as KotlinDuration
import okhttp3.Protocol.HTTP_1_1
import okhttp3.Protocol.HTTP_2
import okhttp3.internal.asFactory
import okhttp3.internal.checkDuration
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.connection.RealCall
import okhttp3.internal.connection.RouteDatabase
import okhttp3.internal.immutableListOf
import okhttp3.internal.platform.Platform
import okhttp3.internal.proxy.NullProxySelector
import okhttp3.internal.tls.CertificateChainCleaner
import okhttp3.internal.tls.OkHostnameVerifier
import okhttp3.internal.toImmutableList
import okhttp3.internal.ws.RealWebSocket
import okio.Sink
import okio.Source
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
/**
* Factory for [calls][Call], which can be used to send HTTP requests and read their responses.
*
* ## OkHttpClients Should Be Shared
*
* OkHttp performs best when you create a single `OkHttpClient` instance and reuse it for all of
* your HTTP calls. This is because each client holds its own connection pool and thread pools.
* Reusing connections and threads reduces latency and saves memory. Conversely, creating a client
* for each request wastes resources on idle pools.
*
* Use `new OkHttpClient()` to create a shared instance with the default settings:
*
* ```java
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient();
* ```
*
* Or use `new OkHttpClient.Builder()` to create a shared instance with custom settings:
*
* ```java
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient.Builder()
* .addInterceptor(new HttpLoggingInterceptor())
* .cache(new Cache(cacheDir, cacheSize))
* .build();
* ```
*
* ## Customize Your Client With newBuilder()
*
* You can customize a shared OkHttpClient instance with [newBuilder]. This builds a client that
* shares the same connection pool, thread pools, and configuration. Use the builder methods to
* add configuration to the derived client for a specific purpose.
*
* This example shows the single instance with default configurations.
*
* ```java
* public final OkHttpClient client = new OkHttpClient.Builder()
* .readTimeout(1000, TimeUnit.MILLISECONDS)
* .writeTimeout(1000, TimeUnit.MILLISECONDS)
* .build();
* ```
*
* This example shows a call with a short 500 millisecond read timeout and a 1000 millisecond
* write timeout. Original configuration is kept, but can be overriden.
*
* ```java
* OkHttpClient eagerClient = client.newBuilder()
* .readTimeout(500, TimeUnit.MILLISECONDS)
* .build();
* Response response = eagerClient.newCall(request).execute();
* ```
*
* ## Shutdown Isn't Necessary
*
* The threads and connections that are held will be released automatically if they remain idle. But
* if you are writing a application that needs to aggressively release unused resources you may do
* so.
*
* Shutdown the dispatcher's executor service with [shutdown()][ExecutorService.shutdown]. This will
* also cause future calls to the client to be rejected.
*
* ```java
* client.dispatcher().executorService().shutdown();
* ```
*
* Clear the connection pool with [evictAll()][ConnectionPool.evictAll]. Note that the connection
* pool's daemon thread may not exit immediately.
*
* ```java
* client.connectionPool().evictAll();
* ```
*
* If your client has a cache, call [close()][Cache.close]. Note that it is an error to create calls
* against a cache that is closed, and doing so will cause the call to crash.
*
* ```java
* client.cache().close();
* ```
*
* OkHttp also uses daemon threads for HTTP/2 connections. These will exit automatically if they
* remain idle.
*/
open class OkHttpClient internal constructor(
builder: Builder,
) : Call.Factory, WebSocket.Factory {
@get:JvmName("dispatcher")
val dispatcher: Dispatcher = builder.dispatcher
/**
* Returns an immutable list of interceptors that observe the full span of each call: from before
* the connection is established (if any) until after the response source is selected (either the
* origin server, cache, or both).
*/
@get:JvmName("interceptors")
val interceptors: List<Interceptor> =
builder.interceptors.toImmutableList()
/**
* Returns an immutable list of interceptors that observe a single network request and response.
* These interceptors must call [Interceptor.Chain.proceed] exactly once: it is an error for
* a network interceptor to short-circuit or repeat a network request.
*/
@get:JvmName("networkInterceptors")
val networkInterceptors: List<Interceptor> =
builder.networkInterceptors.toImmutableList()
@get:JvmName("eventListenerFactory")
val eventListenerFactory: EventListener.Factory =
builder.eventListenerFactory
@get:JvmName("retryOnConnectionFailure")
val retryOnConnectionFailure: Boolean =
builder.retryOnConnectionFailure
@get:JvmName("fastFallback")
val fastFallback: Boolean = builder.fastFallback
@get:JvmName("authenticator")
val authenticator: Authenticator = builder.authenticator
@get:JvmName("followRedirects")
val followRedirects: Boolean = builder.followRedirects
@get:JvmName("followSslRedirects")
val followSslRedirects: Boolean = builder.followSslRedirects
@get:JvmName("cookieJar")
val cookieJar: CookieJar = builder.cookieJar
@get:JvmName("cache")
val cache: Cache? = builder.cache
@get:JvmName("dns")
val dns: Dns = builder.dns
@get:JvmName("proxy")
val proxy: Proxy? = builder.proxy
@get:JvmName("proxySelector")
val proxySelector: ProxySelector =
when {
// Defer calls to ProxySelector.getDefault() because it can throw a SecurityException.
builder.proxy != null -> NullProxySelector
else -> builder.proxySelector ?: ProxySelector.getDefault() ?: NullProxySelector
}
@get:JvmName("proxyAuthenticator")
val proxyAuthenticator: Authenticator =
builder.proxyAuthenticator
@get:JvmName("socketFactory")
val socketFactory: SocketFactory = builder.socketFactory
private val sslSocketFactoryOrNull: SSLSocketFactory?
@get:JvmName("sslSocketFactory")
val sslSocketFactory: SSLSocketFactory
get() = sslSocketFactoryOrNull ?: throw IllegalStateException("CLEARTEXT-only client")
@get:JvmName("x509TrustManager")
val x509TrustManager: X509TrustManager?
@get:JvmName("connectionSpecs")
val connectionSpecs: List<ConnectionSpec> =
builder.connectionSpecs
@get:JvmName("protocols")
val protocols: List<Protocol> = builder.protocols
@get:JvmName("hostnameVerifier")
val hostnameVerifier: HostnameVerifier = builder.hostnameVerifier
@get:JvmName("certificatePinner")
val certificatePinner: CertificatePinner
@get:JvmName("certificateChainCleaner")
val certificateChainCleaner: CertificateChainCleaner?
/**
* Default call timeout (in milliseconds). By default there is no timeout for complete calls, but
* there is for the connect, write, and read actions within a call.
*
* For WebSockets and duplex calls the timeout only applies to the initial setup.
*/
@get:JvmName("callTimeoutMillis")
val callTimeoutMillis: Int = builder.callTimeout
/** Default connect timeout (in milliseconds). The default is 10 seconds. */
@get:JvmName("connectTimeoutMillis")
val connectTimeoutMillis: Int = builder.connectTimeout
/** Default read timeout (in milliseconds). The default is 10 seconds. */
@get:JvmName("readTimeoutMillis")
val readTimeoutMillis: Int = builder.readTimeout
/** Default write timeout (in milliseconds). The default is 10 seconds. */
@get:JvmName("writeTimeoutMillis")
val writeTimeoutMillis: Int = builder.writeTimeout
/** Web socket and HTTP/2 ping interval (in milliseconds). By default pings are not sent. */
@get:JvmName("pingIntervalMillis")
val pingIntervalMillis: Int = builder.pingInterval
/** Web socket close timeout (in milliseconds). */
@get:JvmName("webSocketCloseTimeout")
val webSocketCloseTimeout: Int = builder.webSocketCloseTimeout
/**
* Minimum outbound web socket message size (in bytes) that will be compressed.
* The default is 1024 bytes.
*/
@get:JvmName("minWebSocketMessageToCompress")
val minWebSocketMessageToCompress: Long = builder.minWebSocketMessageToCompress
internal val routeDatabase: RouteDatabase = builder.routeDatabase ?: RouteDatabase()
internal val taskRunner: TaskRunner = builder.taskRunner ?: TaskRunner.INSTANCE
@get:JvmName("connectionPool")
val connectionPool: ConnectionPool =
builder.connectionPool ?: ConnectionPool(
readTimeoutMillis = readTimeoutMillis,
writeTimeoutMillis = writeTimeoutMillis,
socketConnectTimeoutMillis = connectTimeoutMillis,
socketReadTimeoutMillis = readTimeoutMillis,
pingIntervalMillis = pingIntervalMillis,
retryOnConnectionFailure = retryOnConnectionFailure,
fastFallback = fastFallback,
routeDatabase = routeDatabase,
).also {
// Cache the pool in the builder so that it will be shared with other clients
builder.connectionPool = it
}
constructor() : this(Builder())
init {
if (connectionSpecs.none { it.isTls }) {
this.sslSocketFactoryOrNull = null
this.certificateChainCleaner = null
this.x509TrustManager = null
this.certificatePinner = CertificatePinner.DEFAULT
} else if (builder.sslSocketFactoryOrNull != null) {
this.sslSocketFactoryOrNull = builder.sslSocketFactoryOrNull
this.certificateChainCleaner = builder.certificateChainCleaner!!
this.x509TrustManager = builder.x509TrustManagerOrNull!!
this.certificatePinner =
builder.certificatePinner
.withCertificateChainCleaner(certificateChainCleaner!!)
} else {
this.x509TrustManager = Platform.get().platformTrustManager()
this.sslSocketFactoryOrNull = Platform.get().newSslSocketFactory(x509TrustManager!!)
this.certificateChainCleaner = CertificateChainCleaner.get(x509TrustManager!!)
this.certificatePinner =
builder.certificatePinner
.withCertificateChainCleaner(certificateChainCleaner!!)
}
verifyClientState()
}
/**
* Creates an [Address] of out of the provided [HttpUrl]
* that uses this client’s DNS, TLS, and proxy configuration.
*/
fun address(url: HttpUrl): Address {
var useSslSocketFactory: SSLSocketFactory? = null
var useHostnameVerifier: HostnameVerifier? = null
var useCertificatePinner: CertificatePinner? = null
if (url.isHttps) {
useSslSocketFactory = sslSocketFactory
useHostnameVerifier = hostnameVerifier
useCertificatePinner = certificatePinner
}
return Address(
uriHost = url.host,
uriPort = url.port,
dns = dns,
socketFactory = socketFactory,
sslSocketFactory = useSslSocketFactory,
hostnameVerifier = useHostnameVerifier,
certificatePinner = useCertificatePinner,
proxyAuthenticator = proxyAuthenticator,
proxy = proxy,
protocols = protocols,
connectionSpecs = connectionSpecs,
proxySelector = proxySelector,
)
}
private fun verifyClientState() {
check(null !in (interceptors as List<Interceptor?>)) {
"Null interceptor: $interceptors"
}
check(null !in (networkInterceptors as List<Interceptor?>)) {
"Null network interceptor: $networkInterceptors"
}
if (connectionSpecs.none { it.isTls }) {
check(sslSocketFactoryOrNull == null)
check(certificateChainCleaner == null)
check(x509TrustManager == null)
check(certificatePinner == CertificatePinner.DEFAULT)
} else {
checkNotNull(sslSocketFactoryOrNull) { "sslSocketFactory == null" }
checkNotNull(certificateChainCleaner) { "certificateChainCleaner == null" }
checkNotNull(x509TrustManager) { "x509TrustManager == null" }
}
}
/** Prepares the [request] to be executed at some point in the future. */
override fun newCall(request: Request): Call = RealCall(this, request, forWebSocket = false)
/** Uses [request] to connect a new web socket. */
override fun newWebSocket(
request: Request,
listener: WebSocketListener,
): WebSocket {
val webSocket =
RealWebSocket(
taskRunner = taskRunner,
originalRequest = request,
listener = listener,
random = Random(),
pingIntervalMillis = pingIntervalMillis.toLong(),
// extensions is always null for clients:
extensions = null,
minimumDeflateSize = minWebSocketMessageToCompress,
webSocketCloseTimeout = webSocketCloseTimeout.toLong(),
)
webSocket.connect(this)
return webSocket
}
open fun newBuilder(): Builder = Builder(this)
@JvmName("-deprecated_dispatcher")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "dispatcher"),
level = DeprecationLevel.ERROR,
)
fun dispatcher(): Dispatcher = dispatcher
@JvmName("-deprecated_connectionPool")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectionPool"),
level = DeprecationLevel.ERROR,
)
fun connectionPool(): ConnectionPool = connectionPool
@JvmName("-deprecated_interceptors")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "interceptors"),
level = DeprecationLevel.ERROR,
)
fun interceptors(): List<Interceptor> = interceptors
@JvmName("-deprecated_networkInterceptors")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "networkInterceptors"),
level = DeprecationLevel.ERROR,
)
fun networkInterceptors(): List<Interceptor> = networkInterceptors
@JvmName("-deprecated_eventListenerFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "eventListenerFactory"),
level = DeprecationLevel.ERROR,
)
fun eventListenerFactory(): EventListener.Factory = eventListenerFactory
@JvmName("-deprecated_retryOnConnectionFailure")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "retryOnConnectionFailure"),
level = DeprecationLevel.ERROR,
)
fun retryOnConnectionFailure(): Boolean = retryOnConnectionFailure
@JvmName("-deprecated_authenticator")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "authenticator"),
level = DeprecationLevel.ERROR,
)
fun authenticator(): Authenticator = authenticator
@JvmName("-deprecated_followRedirects")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "followRedirects"),
level = DeprecationLevel.ERROR,
)
fun followRedirects(): Boolean = followRedirects
@JvmName("-deprecated_followSslRedirects")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "followSslRedirects"),
level = DeprecationLevel.ERROR,
)
fun followSslRedirects(): Boolean = followSslRedirects
@JvmName("-deprecated_cookieJar")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cookieJar"),
level = DeprecationLevel.ERROR,
)
fun cookieJar(): CookieJar = cookieJar
@JvmName("-deprecated_cache")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cache"),
level = DeprecationLevel.ERROR,
)
fun cache(): Cache? = cache
@JvmName("-deprecated_dns")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "dns"),
level = DeprecationLevel.ERROR,
)
fun dns(): Dns = dns
@JvmName("-deprecated_proxy")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxy"),
level = DeprecationLevel.ERROR,
)
fun proxy(): Proxy? = proxy
@JvmName("-deprecated_proxySelector")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxySelector"),
level = DeprecationLevel.ERROR,
)
fun proxySelector(): ProxySelector = proxySelector
@JvmName("-deprecated_proxyAuthenticator")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxyAuthenticator"),
level = DeprecationLevel.ERROR,
)
fun proxyAuthenticator(): Authenticator = proxyAuthenticator
@JvmName("-deprecated_socketFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "socketFactory"),
level = DeprecationLevel.ERROR,
)
fun socketFactory(): SocketFactory = socketFactory
@JvmName("-deprecated_sslSocketFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "sslSocketFactory"),
level = DeprecationLevel.ERROR,
)
fun sslSocketFactory(): SSLSocketFactory = sslSocketFactory
@JvmName("-deprecated_connectionSpecs")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectionSpecs"),
level = DeprecationLevel.ERROR,
)
fun connectionSpecs(): List<ConnectionSpec> = connectionSpecs
@JvmName("-deprecated_protocols")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "protocols"),
level = DeprecationLevel.ERROR,
)
fun protocols(): List<Protocol> = protocols
@JvmName("-deprecated_hostnameVerifier")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "hostnameVerifier"),
level = DeprecationLevel.ERROR,
)
fun hostnameVerifier(): HostnameVerifier = hostnameVerifier
@JvmName("-deprecated_certificatePinner")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "certificatePinner"),
level = DeprecationLevel.ERROR,
)
fun certificatePinner(): CertificatePinner = certificatePinner
@JvmName("-deprecated_callTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "callTimeoutMillis"),
level = DeprecationLevel.ERROR,
)
fun callTimeoutMillis(): Int = callTimeoutMillis
@JvmName("-deprecated_connectTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectTimeoutMillis"),
level = DeprecationLevel.ERROR,
)
fun connectTimeoutMillis(): Int = connectTimeoutMillis
@JvmName("-deprecated_readTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "readTimeoutMillis"),
level = DeprecationLevel.ERROR,
)
fun readTimeoutMillis(): Int = readTimeoutMillis
@JvmName("-deprecated_writeTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "writeTimeoutMillis"),
level = DeprecationLevel.ERROR,
)
fun writeTimeoutMillis(): Int = writeTimeoutMillis
@JvmName("-deprecated_pingIntervalMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "pingIntervalMillis"),
level = DeprecationLevel.ERROR,
)
fun pingIntervalMillis(): Int = pingIntervalMillis
class Builder() {
internal var dispatcher: Dispatcher = Dispatcher()
internal var connectionPool: ConnectionPool? = null
internal val interceptors: MutableList<Interceptor> = mutableListOf()
internal val networkInterceptors: MutableList<Interceptor> = mutableListOf()
internal var eventListenerFactory: EventListener.Factory = EventListener.NONE.asFactory()
internal var retryOnConnectionFailure = true
internal var fastFallback = true
internal var authenticator: Authenticator = Authenticator.NONE
internal var followRedirects = true
internal var followSslRedirects = true
internal var cookieJar: CookieJar = CookieJar.NO_COOKIES
internal var cache: Cache? = null
internal var dns: Dns = Dns.SYSTEM
internal var proxy: Proxy? = null
internal var proxySelector: ProxySelector? = null
internal var proxyAuthenticator: Authenticator = Authenticator.NONE
internal var socketFactory: SocketFactory = SocketFactory.getDefault()
internal var sslSocketFactoryOrNull: SSLSocketFactory? = null
internal var x509TrustManagerOrNull: X509TrustManager? = null
internal var connectionSpecs: List<ConnectionSpec> = DEFAULT_CONNECTION_SPECS
internal var protocols: List<Protocol> = DEFAULT_PROTOCOLS
internal var hostnameVerifier: HostnameVerifier = OkHostnameVerifier
internal var certificatePinner: CertificatePinner = CertificatePinner.DEFAULT
internal var certificateChainCleaner: CertificateChainCleaner? = null
internal var callTimeout = 0
internal var connectTimeout = 10_000
internal var readTimeout = 10_000
internal var writeTimeout = 10_000
internal var pingInterval = 0
internal var webSocketCloseTimeout = RealWebSocket.CANCEL_AFTER_CLOSE_MILLIS.toInt()
internal var minWebSocketMessageToCompress = RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE
internal var routeDatabase: RouteDatabase? = null
internal var taskRunner: TaskRunner? = null
internal constructor(okHttpClient: OkHttpClient) : this() {
this.dispatcher = okHttpClient.dispatcher
this.connectionPool = okHttpClient.connectionPool
this.interceptors += okHttpClient.interceptors
this.networkInterceptors += okHttpClient.networkInterceptors
this.eventListenerFactory = okHttpClient.eventListenerFactory
this.retryOnConnectionFailure = okHttpClient.retryOnConnectionFailure
this.fastFallback = okHttpClient.fastFallback
this.authenticator = okHttpClient.authenticator
this.followRedirects = okHttpClient.followRedirects
this.followSslRedirects = okHttpClient.followSslRedirects
this.cookieJar = okHttpClient.cookieJar
this.cache = okHttpClient.cache
this.dns = okHttpClient.dns
this.proxy = okHttpClient.proxy
this.proxySelector = okHttpClient.proxySelector
this.proxyAuthenticator = okHttpClient.proxyAuthenticator
this.socketFactory = okHttpClient.socketFactory
this.sslSocketFactoryOrNull = okHttpClient.sslSocketFactoryOrNull
this.x509TrustManagerOrNull = okHttpClient.x509TrustManager
this.connectionSpecs = okHttpClient.connectionSpecs
this.protocols = okHttpClient.protocols
this.hostnameVerifier = okHttpClient.hostnameVerifier
this.certificatePinner = okHttpClient.certificatePinner
this.certificateChainCleaner = okHttpClient.certificateChainCleaner
this.callTimeout = okHttpClient.callTimeoutMillis
this.connectTimeout = okHttpClient.connectTimeoutMillis
this.readTimeout = okHttpClient.readTimeoutMillis
this.writeTimeout = okHttpClient.writeTimeoutMillis
this.pingInterval = okHttpClient.pingIntervalMillis
this.webSocketCloseTimeout = okHttpClient.webSocketCloseTimeout
this.minWebSocketMessageToCompress = okHttpClient.minWebSocketMessageToCompress
this.routeDatabase = okHttpClient.routeDatabase
this.taskRunner = okHttpClient.taskRunner
}
/**
* Sets the dispatcher used to set policy and execute asynchronous requests. Must not be null.
*/
fun dispatcher(dispatcher: Dispatcher) =
apply {
this.dispatcher = dispatcher
}
/**
* Sets the connection pool used to recycle HTTP and HTTPS connections.
*
* If unset, a new connection pool will be used.
*/
fun connectionPool(connectionPool: ConnectionPool) =
apply {
this.connectionPool = connectionPool
}
/**
* Returns a modifiable list of interceptors that observe the full span of each call: from
* before the connection is established (if any) until after the response source is selected
* (either the origin server, cache, or both).
*/
fun interceptors(): MutableList<Interceptor> = interceptors
fun addInterceptor(interceptor: Interceptor) =
apply {
interceptors += interceptor
}
@JvmName("-addInterceptor") // Prefix with '-' to prevent ambiguous overloads from Java.
inline fun addInterceptor(crossinline block: (chain: Interceptor.Chain) -> Response) =
addInterceptor(Interceptor { chain -> block(chain) })
/**
* Returns a modifiable list of interceptors that observe a single network request and response.
* These interceptors must call [Interceptor.Chain.proceed] exactly once: it is an error for a
* network interceptor to short-circuit or repeat a network request.
*/
fun networkInterceptors(): MutableList<Interceptor> = networkInterceptors
fun addNetworkInterceptor(interceptor: Interceptor) =
apply {
networkInterceptors += interceptor
}
@JvmName("-addNetworkInterceptor") // Prefix with '-' to prevent ambiguous overloads from Java.
inline fun addNetworkInterceptor(crossinline block: (chain: Interceptor.Chain) -> Response) =
addNetworkInterceptor(Interceptor { chain -> block(chain) })
/**
* Configure a single client scoped listener that will receive all analytic events for this
* client.
*
* @see EventListener for semantics and restrictions on listener implementations.
*/
fun eventListener(eventListener: EventListener) =
apply {
this.eventListenerFactory = eventListener.asFactory()
}
/**
* Configure a factory to provide per-call scoped listeners that will receive analytic events
* for this client.
*
* @see EventListener for semantics and restrictions on listener implementations.
*/
fun eventListenerFactory(eventListenerFactory: EventListener.Factory) =
apply {
this.eventListenerFactory = eventListenerFactory
}
/**
* Configure this client to retry or not when a connectivity problem is encountered. By default,
* this client silently recovers from the following problems:
*
* * **Unreachable IP addresses.** If the URL's host has multiple IP addresses,
* failure to reach any individual IP address doesn't fail the overall request. This can
* increase availability of multi-homed services.
*
* * **Stale pooled connections.** The [ConnectionPool] reuses sockets
* to decrease request latency, but these connections will occasionally time out.
*
* * **Unreachable proxy servers.** A [ProxySelector] can be used to
* attempt multiple proxy servers in sequence, eventually falling back to a direct
* connection.
*
* Set this to false to avoid retrying requests when doing so is destructive. In this case the
* calling application should do its own recovery of connectivity failures.
*/
fun retryOnConnectionFailure(retryOnConnectionFailure: Boolean) =
apply {
this.retryOnConnectionFailure = retryOnConnectionFailure
}
/**
* Configure this client to perform fast fallbacks by attempting multiple connections
* concurrently, returning once any connection connects successfully.
*
* This implements Happy Eyeballs ([RFC 6555][rfc_6555]), balancing connect latency vs.
* wasted resources.
*
* Defaults to enabled, call with [fastFallback] = false to revert to 4.x behaviour.
*
* [rfc_6555]: https://datatracker.ietf.org/doc/html/rfc6555
*/
fun fastFallback(fastFallback: Boolean) =
apply {
this.fastFallback = fastFallback
}
/**
* Sets the authenticator used to respond to challenges from origin servers. Use
* [proxyAuthenticator] to set the authenticator for proxy servers.
*
* If unset, the [no authentication will be attempted][Authenticator.NONE].
*/
fun authenticator(authenticator: Authenticator) =
apply {
this.authenticator = authenticator
}
/** Configure this client to follow redirects. If unset, redirects will be followed. */
fun followRedirects(followRedirects: Boolean) =
apply {
this.followRedirects = followRedirects
}
/**
* Configure this client to allow protocol redirects from HTTPS to HTTP and from HTTP to HTTPS.
* Redirects are still first restricted by [followRedirects]. Defaults to true.
*
* @param followProtocolRedirects whether to follow redirects between HTTPS and HTTP.
*/
fun followSslRedirects(followProtocolRedirects: Boolean) =
apply {
this.followSslRedirects = followProtocolRedirects
}
/**
* Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to
* outgoing HTTP requests.
*
* If unset, [no cookies][CookieJar.NO_COOKIES] will be accepted nor provided.
*/
fun cookieJar(cookieJar: CookieJar) =
apply {
this.cookieJar = cookieJar
}
/** Sets the response cache to be used to read and write cached responses. */
fun cache(cache: Cache?) =
apply {
this.cache = cache
}
internal fun taskRunner(taskRunner: TaskRunner) =
apply {
this.taskRunner = taskRunner
}
/**
* Sets the DNS service used to lookup IP addresses for hostnames.
*
* If unset, the [system-wide default][Dns.SYSTEM] DNS will be used.
*/
fun dns(dns: Dns) =
apply {
if (dns != this.dns) {
this.routeDatabase = null
}
this.dns = dns
}
/**
* Sets the HTTP proxy that will be used by connections created by this client. This takes
* precedence over [proxySelector], which is only honored when this proxy is null (which it is
* by default). To disable proxy use completely, call `proxy(Proxy.NO_PROXY)`.
*/
fun proxy(proxy: Proxy?) =
apply {
if (proxy != this.proxy) {
this.routeDatabase = null
}
this.proxy = proxy
}
/**
* Sets the proxy selection policy to be used if no [proxy][proxy] is specified explicitly. The
* proxy selector may return multiple proxies; in that case they will be tried in sequence until
* a successful connection is established.
*
* If unset, the [system-wide default][ProxySelector.getDefault] proxy selector will be used.
*/
fun proxySelector(proxySelector: ProxySelector) =
apply {
if (proxySelector != this.proxySelector) {
this.routeDatabase = null
}
this.proxySelector = proxySelector
}
/**
* Sets the authenticator used to respond to challenges from proxy servers. Use [authenticator]
* to set the authenticator for origin servers.
*
* If unset, the [no authentication will be attempted][Authenticator.NONE].
*/
fun proxyAuthenticator(proxyAuthenticator: Authenticator) =
apply {
if (proxyAuthenticator != this.proxyAuthenticator) {
this.routeDatabase = null
}
this.proxyAuthenticator = proxyAuthenticator
}
/**
* Sets the socket factory used to create connections. OkHttp only uses the parameterless
* [SocketFactory.createSocket] method to create unconnected sockets. Overriding this method,
* e. g., allows the socket to be bound to a specific local address.
*
* If unset, the [system-wide default][SocketFactory.getDefault] socket factory will be used.
*/
fun socketFactory(socketFactory: SocketFactory) =
apply {
require(socketFactory !is SSLSocketFactory) { "socketFactory instanceof SSLSocketFactory" }
if (socketFactory != this.socketFactory) {
this.routeDatabase = null
}
this.socketFactory = socketFactory
}
/**
* Sets the socket factory used to secure HTTPS connections. If unset, the system default will
* be used.
*
* @deprecated [SSLSocketFactory] does not expose its [X509TrustManager], which is a field that
* OkHttp needs to build a clean certificate chain. This method instead must use reflection
* to extract the trust manager. Applications should prefer to call
* `sslSocketFactory(SSLSocketFactory, X509TrustManager)`, which avoids such reflection.
*/
@Deprecated(
message = "Use the sslSocketFactory overload that accepts a X509TrustManager.",
level = DeprecationLevel.ERROR,
)
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory) =
apply {
if (sslSocketFactory != this.sslSocketFactoryOrNull) {
this.routeDatabase = null
}
this.sslSocketFactoryOrNull = sslSocketFactory
this.x509TrustManagerOrNull =
Platform.get().trustManager(sslSocketFactory) ?: throw IllegalStateException(
"Unable to extract the trust manager on ${Platform.get()}, " +
"sslSocketFactory is ${sslSocketFactory.javaClass}",
)
this.certificateChainCleaner =
Platform.get().buildCertificateChainCleaner(x509TrustManagerOrNull!!)
}
/**
* Sets the socket factory and trust manager used to secure HTTPS connections. If unset, the
* system defaults will be used.
*
* Most applications should not call this method, and instead use the system defaults. Those
* classes include special optimizations that can be lost if the implementations are decorated.
*
* If necessary, you can create and configure the defaults yourself with the following code:
*
* ```java
* TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
* TrustManagerFactory.getDefaultAlgorithm());
* trustManagerFactory.init((KeyStore) null);
* TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
* if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
* throw new IllegalStateException("Unexpected default trust managers:"
* + Arrays.toString(trustManagers));
* }
* X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
*
* SSLContext sslContext = SSLContext.getInstance("TLS");
* sslContext.init(null, new TrustManager[] { trustManager }, null);
* SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
*
* OkHttpClient client = new OkHttpClient.Builder()
* .sslSocketFactory(sslSocketFactory, trustManager)
* .build();
* ```
*
* ## TrustManagers on Android are Weird!
*
* Trust managers targeting Android must also define a method that has this signature:
*
* ```java
* @SuppressWarnings("unused")
* public List<X509Certificate> checkServerTrusted(
* X509Certificate[] chain, String authType, String host) throws CertificateException {
* }
* ```
*
* This method works like [X509TrustManager.checkServerTrusted] but it receives the hostname of
* the server as an extra parameter. Regardless of what checks this method performs, OkHttp will
* always check that the server's certificates match its hostname using the [HostnameVerifier].
* See [android.net.http.X509TrustManagerExtensions] for more information.
*/
fun sslSocketFactory(
sslSocketFactory: SSLSocketFactory,
trustManager: X509TrustManager,
) = apply {
if (sslSocketFactory != this.sslSocketFactoryOrNull || trustManager != this.x509TrustManagerOrNull) {
this.routeDatabase = null
}
this.sslSocketFactoryOrNull = sslSocketFactory
this.certificateChainCleaner = CertificateChainCleaner.get(trustManager)
this.x509TrustManagerOrNull = trustManager
}
fun connectionSpecs(connectionSpecs: List<ConnectionSpec>) =
apply {
if (connectionSpecs != this.connectionSpecs) {
this.routeDatabase = null
}
this.connectionSpecs = connectionSpecs.toImmutableList()
}
/**
* Configure the protocols used by this client to communicate with remote servers. By default
* this client will prefer the most efficient transport available, falling back to more