1
0
mirror of https://github.com/square/okhttp.git synced 2025-07-31 05:04:26 +03:00

Use vals in OkHttpClient

This commit is contained in:
Jesse Wilson
2019-05-25 10:34:25 -04:00
parent 8e96075fcd
commit 9c20f17270
10 changed files with 323 additions and 153 deletions

View File

@ -218,7 +218,7 @@ class Main : Runnable {
} }
private fun close() { private fun close() {
client.connectionPool().evictAll() // Close any persistent connections. client.connectionPool.evictAll() // Close any persistent connections.
} }
companion object { companion object {

View File

@ -196,7 +196,7 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
} }
private fun getCacheOnlyResponse(request: Request): Response? { private fun getCacheOnlyResponse(request: Request): Response? {
if (!post && client.cache() != null) { if (!post && client.cache != null) {
try { try {
val cacheRequest = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build() val cacheRequest = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build()

View File

@ -120,55 +120,103 @@ import kotlin.DeprecationLevel.ERROR
open class OkHttpClient internal constructor( open class OkHttpClient internal constructor(
builder: Builder builder: Builder
) : Cloneable, Call.Factory, WebSocket.Factory { ) : Cloneable, Call.Factory, WebSocket.Factory {
private val dispatcher: Dispatcher = builder.dispatcher
private val connectionPool: ConnectionPool = builder.connectionPool @get:JvmName("dispatcher") val dispatcher: Dispatcher = builder.dispatcher
private val interceptors: List<Interceptor> = builder.interceptors.toImmutableList()
private val networkInterceptors: List<Interceptor> = builder.networkInterceptors.toImmutableList() @get:JvmName("connectionPool") val connectionPool: ConnectionPool = builder.connectionPool
private val eventListenerFactory: EventListener.Factory = builder.eventListenerFactory
private val retryOnConnectionFailure: Boolean = builder.retryOnConnectionFailure /**
private val authenticator: Authenticator = builder.authenticator * Returns an immutable list of interceptors that observe the full span of each call: from before
private val followRedirects: Boolean = builder.followRedirects * the connection is established (if any) until after the response source is selected (either the
private val followSslRedirects: Boolean = builder.followSslRedirects * origin server, cache, or both).
private val cookieJar: CookieJar = builder.cookieJar */
private val cache: Cache? = builder.cache @get:JvmName("interceptors") val interceptors: List<Interceptor> =
private val dns: Dns = builder.dns builder.interceptors.toImmutableList()
private val proxy: Proxy? = builder.proxy
private val proxySelector: ProxySelector = builder.proxySelector /**
private val proxyAuthenticator: Authenticator = builder.proxyAuthenticator * Returns an immutable list of interceptors that observe a single network request and response.
private val socketFactory: SocketFactory = builder.socketFactory * These interceptors must call [Interceptor.Chain.proceed] exactly once: it is an error for
private val sslSocketFactory: SSLSocketFactory? * a network interceptor to short-circuit or repeat a network request.
private val connectionSpecs: List<ConnectionSpec> = builder.connectionSpecs */
private val protocols: List<Protocol> = builder.protocols @get:JvmName("networkInterceptors") val networkInterceptors: List<Interceptor> =
private val hostnameVerifier: HostnameVerifier = builder.hostnameVerifier builder.networkInterceptors.toImmutableList()
private val certificatePinner: CertificatePinner
private val certificateChainCleaner: CertificateChainCleaner? @get:JvmName("eventListenerFactory") val eventListenerFactory: EventListener.Factory =
private val callTimeout: Int = builder.callTimeout builder.eventListenerFactory
private val connectTimeout: Int = builder.connectTimeout
private val readTimeout: Int = builder.readTimeout @get:JvmName("retryOnConnectionFailure") val retryOnConnectionFailure: Boolean =
private val writeTimeout: Int = builder.writeTimeout builder.retryOnConnectionFailure
private val pingInterval: Int = builder.pingInterval
@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 = builder.proxySelector
@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("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.
*/
@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
constructor() : this(Builder()) constructor() : this(Builder())
init { init {
var isTLS = false if (builder.sslSocketFactoryOrNull != null || connectionSpecs.none { it.isTls }) {
for (spec in connectionSpecs) { this.sslSocketFactoryOrNull = builder.sslSocketFactoryOrNull
isTLS = isTLS || spec.isTls
}
// TODO - these nullability warnings existed in Java
if (builder.sslSocketFactory != null || !isTLS) {
this.sslSocketFactory = builder.sslSocketFactory
this.certificateChainCleaner = builder.certificateChainCleaner this.certificateChainCleaner = builder.certificateChainCleaner
} else { } else {
val trustManager = Platform.get().platformTrustManager() val trustManager = Platform.get().platformTrustManager()
Platform.get().configureTrustManager(trustManager) Platform.get().configureTrustManager(trustManager)
this.sslSocketFactory = newSslSocketFactory(trustManager) this.sslSocketFactoryOrNull = newSslSocketFactory(trustManager)
this.certificateChainCleaner = CertificateChainCleaner.get(trustManager) this.certificateChainCleaner = CertificateChainCleaner.get(trustManager)
} }
if (sslSocketFactory != null) { if (sslSocketFactoryOrNull != null) {
Platform.get().configureSslSocketFactory(sslSocketFactory) Platform.get().configureSslSocketFactory(sslSocketFactoryOrNull)
} }
this.certificatePinner = builder.certificatePinner this.certificatePinner = builder.certificatePinner
@ -182,76 +230,6 @@ open class OkHttpClient internal constructor(
} }
} }
fun dispatcher(): Dispatcher = dispatcher
fun connectionPool(): ConnectionPool = connectionPool
/**
* 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).
*/
fun interceptors(): List<Interceptor> = interceptors
/**
* 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.
*/
fun networkInterceptors(): List<Interceptor> = networkInterceptors
fun eventListenerFactory(): EventListener.Factory = eventListenerFactory
fun retryOnConnectionFailure(): Boolean = retryOnConnectionFailure
fun authenticator(): Authenticator = authenticator
fun followRedirects(): Boolean = followRedirects
fun followSslRedirects(): Boolean = followSslRedirects
fun cookieJar(): CookieJar = cookieJar
fun cache(): Cache? = cache
fun dns(): Dns = dns
fun proxy(): Proxy? = proxy
fun proxySelector(): ProxySelector = proxySelector
fun proxyAuthenticator(): Authenticator = proxyAuthenticator
fun socketFactory(): SocketFactory = socketFactory
fun sslSocketFactory(): SSLSocketFactory = sslSocketFactory!!
fun connectionSpecs(): List<ConnectionSpec> = connectionSpecs
fun protocols(): List<Protocol> = protocols
fun hostnameVerifier(): HostnameVerifier = hostnameVerifier
fun certificatePinner(): CertificatePinner = certificatePinner
/**
* 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.
*/
fun callTimeoutMillis(): Int = callTimeout
/** Default connect timeout (in milliseconds). The default is 10 seconds. */
fun connectTimeoutMillis(): Int = connectTimeout
/** Default read timeout (in milliseconds). The default is 10 seconds. */
fun readTimeoutMillis(): Int = readTimeout
/** Default write timeout (in milliseconds). The default is 10 seconds. */
fun writeTimeoutMillis(): Int = writeTimeout
/** Web socket and HTTP/2 ping interval (in milliseconds). By default pings are not sent. */
fun pingIntervalMillis(): Int = pingInterval
/** Prepares the [request] to be executed at some point in the future. */ /** Prepares the [request] to be executed at some point in the future. */
override fun newCall(request: Request): Call { override fun newCall(request: Request): Call {
return RealCall.newRealCall(this, request, forWebSocket = false) return RealCall.newRealCall(this, request, forWebSocket = false)
@ -259,13 +237,195 @@ open class OkHttpClient internal constructor(
/** Uses [request] to connect a new web socket. */ /** Uses [request] to connect a new web socket. */
override fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket { override fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket {
val webSocket = RealWebSocket(request, listener, Random(), pingInterval.toLong()) val webSocket = RealWebSocket(request, listener, Random(), pingIntervalMillis.toLong())
webSocket.connect(this) webSocket.connect(this)
return webSocket return webSocket
} }
open fun newBuilder(): Builder = Builder(this) open fun newBuilder(): Builder = Builder(this)
@JvmName("-deprecated_dispatcher")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "dispatcher"),
level = DeprecationLevel.WARNING)
fun dispatcher(): Dispatcher = dispatcher
@JvmName("-deprecated_connectionPool")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectionPool"),
level = DeprecationLevel.WARNING)
fun connectionPool(): ConnectionPool = connectionPool
@JvmName("-deprecated_interceptors")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "interceptors"),
level = DeprecationLevel.WARNING)
fun interceptors(): List<Interceptor> = interceptors
@JvmName("-deprecated_networkInterceptors")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "networkInterceptors"),
level = DeprecationLevel.WARNING)
fun networkInterceptors(): List<Interceptor> = networkInterceptors
@JvmName("-deprecated_eventListenerFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "eventListenerFactory"),
level = DeprecationLevel.WARNING)
fun eventListenerFactory(): EventListener.Factory = eventListenerFactory
@JvmName("-deprecated_retryOnConnectionFailure")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "retryOnConnectionFailure"),
level = DeprecationLevel.WARNING)
fun retryOnConnectionFailure(): Boolean = retryOnConnectionFailure
@JvmName("-deprecated_authenticator")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "authenticator"),
level = DeprecationLevel.WARNING)
fun authenticator(): Authenticator = authenticator
@JvmName("-deprecated_followRedirects")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "followRedirects"),
level = DeprecationLevel.WARNING)
fun followRedirects(): Boolean = followRedirects
@JvmName("-deprecated_followSslRedirects")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "followSslRedirects"),
level = DeprecationLevel.WARNING)
fun followSslRedirects(): Boolean = followSslRedirects
@JvmName("-deprecated_cookieJar")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cookieJar"),
level = DeprecationLevel.WARNING)
fun cookieJar(): CookieJar = cookieJar
@JvmName("-deprecated_cache")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "cache"),
level = DeprecationLevel.WARNING)
fun cache(): Cache? = cache
@JvmName("-deprecated_dns")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "dns"),
level = DeprecationLevel.WARNING)
fun dns(): Dns = dns
@JvmName("-deprecated_proxy")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxy"),
level = DeprecationLevel.WARNING)
fun proxy(): Proxy? = proxy
@JvmName("-deprecated_proxySelector")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxySelector"),
level = DeprecationLevel.WARNING)
fun proxySelector(): ProxySelector = proxySelector
@JvmName("-deprecated_proxyAuthenticator")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "proxyAuthenticator"),
level = DeprecationLevel.WARNING)
fun proxyAuthenticator(): Authenticator = proxyAuthenticator
@JvmName("-deprecated_socketFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "socketFactory"),
level = DeprecationLevel.WARNING)
fun socketFactory(): SocketFactory = socketFactory
@JvmName("-deprecated_sslSocketFactory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "sslSocketFactory"),
level = DeprecationLevel.WARNING)
fun sslSocketFactory(): SSLSocketFactory = sslSocketFactory
@JvmName("-deprecated_connectionSpecs")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectionSpecs"),
level = DeprecationLevel.WARNING)
fun connectionSpecs(): List<ConnectionSpec> = connectionSpecs
@JvmName("-deprecated_protocols")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "protocols"),
level = DeprecationLevel.WARNING)
fun protocols(): List<Protocol> = protocols
@JvmName("-deprecated_hostnameVerifier")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "hostnameVerifier"),
level = DeprecationLevel.WARNING)
fun hostnameVerifier(): HostnameVerifier = hostnameVerifier
@JvmName("-deprecated_certificatePinner")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "certificatePinner"),
level = DeprecationLevel.WARNING)
fun certificatePinner(): CertificatePinner = certificatePinner
@JvmName("-deprecated_callTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "callTimeoutMillis"),
level = DeprecationLevel.WARNING)
fun callTimeoutMillis(): Int = callTimeoutMillis
@JvmName("-deprecated_connectTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "connectTimeoutMillis"),
level = DeprecationLevel.WARNING)
fun connectTimeoutMillis(): Int = connectTimeoutMillis
@JvmName("-deprecated_readTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "readTimeoutMillis"),
level = DeprecationLevel.WARNING)
fun readTimeoutMillis(): Int = readTimeoutMillis
@JvmName("-deprecated_writeTimeoutMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "writeTimeoutMillis"),
level = DeprecationLevel.WARNING)
fun writeTimeoutMillis(): Int = writeTimeoutMillis
@JvmName("-deprecated_pingIntervalMillis")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "pingIntervalMillis"),
level = DeprecationLevel.WARNING)
fun pingIntervalMillis(): Int = pingIntervalMillis
class Builder constructor() { class Builder constructor() {
internal var dispatcher: Dispatcher = Dispatcher() internal var dispatcher: Dispatcher = Dispatcher()
internal var connectionPool: ConnectionPool = ConnectionPool() internal var connectionPool: ConnectionPool = ConnectionPool()
@ -283,7 +443,7 @@ open class OkHttpClient internal constructor(
internal var proxySelector: ProxySelector = ProxySelector.getDefault() ?: NullProxySelector() internal var proxySelector: ProxySelector = ProxySelector.getDefault() ?: NullProxySelector()
internal var proxyAuthenticator: Authenticator = Authenticator.NONE internal var proxyAuthenticator: Authenticator = Authenticator.NONE
internal var socketFactory: SocketFactory = SocketFactory.getDefault() internal var socketFactory: SocketFactory = SocketFactory.getDefault()
internal var sslSocketFactory: SSLSocketFactory? = null internal var sslSocketFactoryOrNull: SSLSocketFactory? = null
internal var connectionSpecs: List<ConnectionSpec> = DEFAULT_CONNECTION_SPECS internal var connectionSpecs: List<ConnectionSpec> = DEFAULT_CONNECTION_SPECS
internal var protocols: List<Protocol> = DEFAULT_PROTOCOLS internal var protocols: List<Protocol> = DEFAULT_PROTOCOLS
internal var hostnameVerifier: HostnameVerifier = OkHostnameVerifier internal var hostnameVerifier: HostnameVerifier = OkHostnameVerifier
@ -312,17 +472,17 @@ open class OkHttpClient internal constructor(
this.proxySelector = okHttpClient.proxySelector this.proxySelector = okHttpClient.proxySelector
this.proxyAuthenticator = okHttpClient.proxyAuthenticator this.proxyAuthenticator = okHttpClient.proxyAuthenticator
this.socketFactory = okHttpClient.socketFactory this.socketFactory = okHttpClient.socketFactory
this.sslSocketFactory = okHttpClient.sslSocketFactory this.sslSocketFactoryOrNull = okHttpClient.sslSocketFactoryOrNull
this.connectionSpecs = okHttpClient.connectionSpecs this.connectionSpecs = okHttpClient.connectionSpecs
this.protocols = okHttpClient.protocols this.protocols = okHttpClient.protocols
this.hostnameVerifier = okHttpClient.hostnameVerifier this.hostnameVerifier = okHttpClient.hostnameVerifier
this.certificatePinner = okHttpClient.certificatePinner this.certificatePinner = okHttpClient.certificatePinner
this.certificateChainCleaner = okHttpClient.certificateChainCleaner this.certificateChainCleaner = okHttpClient.certificateChainCleaner
this.callTimeout = okHttpClient.callTimeout this.callTimeout = okHttpClient.callTimeoutMillis
this.connectTimeout = okHttpClient.connectTimeout this.connectTimeout = okHttpClient.connectTimeoutMillis
this.readTimeout = okHttpClient.readTimeout this.readTimeout = okHttpClient.readTimeoutMillis
this.writeTimeout = okHttpClient.writeTimeout this.writeTimeout = okHttpClient.writeTimeoutMillis
this.pingInterval = okHttpClient.pingInterval this.pingInterval = okHttpClient.pingIntervalMillis
} }
/** /**
@ -538,7 +698,7 @@ open class OkHttpClient internal constructor(
level = ERROR level = ERROR
) )
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory) = apply { fun sslSocketFactory(sslSocketFactory: SSLSocketFactory) = apply {
this.sslSocketFactory = sslSocketFactory this.sslSocketFactoryOrNull = sslSocketFactory
this.certificateChainCleaner = Platform.get().buildCertificateChainCleaner(sslSocketFactory) this.certificateChainCleaner = Platform.get().buildCertificateChainCleaner(sslSocketFactory)
} }
@ -575,7 +735,7 @@ open class OkHttpClient internal constructor(
sslSocketFactory: SSLSocketFactory, sslSocketFactory: SSLSocketFactory,
trustManager: X509TrustManager trustManager: X509TrustManager
) = apply { ) = apply {
this.sslSocketFactory = sslSocketFactory this.sslSocketFactoryOrNull = sslSocketFactory
this.certificateChainCleaner = CertificateChainCleaner.get(trustManager) this.certificateChainCleaner = CertificateChainCleaner.get(trustManager)
} }

View File

@ -62,10 +62,10 @@ internal class RealCall private constructor(
transmitter.timeoutEnter() transmitter.timeoutEnter()
transmitter.callStart() transmitter.callStart()
try { try {
client.dispatcher().executed(this) client.dispatcher.executed(this)
return getResponseWithInterceptorChain() return getResponseWithInterceptorChain()
} finally { } finally {
client.dispatcher().finished(this) client.dispatcher.finished(this)
} }
} }
@ -75,7 +75,7 @@ internal class RealCall private constructor(
executed = true executed = true
} }
transmitter.callStart() transmitter.callStart()
client.dispatcher().enqueue(AsyncCall(responseCallback)) client.dispatcher.enqueue(AsyncCall(responseCallback))
} }
override fun cancel() { override fun cancel() {
@ -111,7 +111,7 @@ internal class RealCall private constructor(
* if the executor has been shut down by reporting the call as failed. * if the executor has been shut down by reporting the call as failed.
*/ */
fun executeOn(executorService: ExecutorService) { fun executeOn(executorService: ExecutorService) {
assert(!Thread.holdsLock(client.dispatcher())) assert(!Thread.holdsLock(client.dispatcher))
var success = false var success = false
try { try {
executorService.execute(this) executorService.execute(this)
@ -123,7 +123,7 @@ internal class RealCall private constructor(
responseCallback.onFailure(this@RealCall, ioException) responseCallback.onFailure(this@RealCall, ioException)
} finally { } finally {
if (!success) { if (!success) {
client.dispatcher().finished(this) // This call is no longer running! client.dispatcher.finished(this) // This call is no longer running!
} }
} }
} }
@ -144,7 +144,7 @@ internal class RealCall private constructor(
responseCallback.onFailure(this@RealCall, e) responseCallback.onFailure(this@RealCall, e)
} }
} finally { } finally {
client.dispatcher().finished(this) client.dispatcher.finished(this)
} }
} }
} }
@ -166,19 +166,18 @@ internal class RealCall private constructor(
fun getResponseWithInterceptorChain(): Response { fun getResponseWithInterceptorChain(): Response {
// Build a full stack of interceptors. // Build a full stack of interceptors.
val interceptors = mutableListOf<Interceptor>() val interceptors = mutableListOf<Interceptor>()
interceptors += client.interceptors() interceptors += client.interceptors
interceptors += RetryAndFollowUpInterceptor(client) interceptors += RetryAndFollowUpInterceptor(client)
interceptors += BridgeInterceptor(client.cookieJar()) interceptors += BridgeInterceptor(client.cookieJar)
interceptors += CacheInterceptor(client.cache()) interceptors += CacheInterceptor(client.cache)
interceptors += ConnectInterceptor interceptors += ConnectInterceptor
if (!forWebSocket) { if (!forWebSocket) {
interceptors += client.networkInterceptors() interceptors += client.networkInterceptors
} }
interceptors += CallServerInterceptor(forWebSocket) interceptors += CallServerInterceptor(forWebSocket)
val chain = RealInterceptorChain(interceptors, transmitter, null, 0, val chain = RealInterceptorChain(interceptors, transmitter, null, 0, originalRequest, this,
originalRequest, this, client.connectTimeoutMillis(), client.connectTimeoutMillis, client.readTimeoutMillis, client.writeTimeoutMillis)
client.readTimeoutMillis(), client.writeTimeoutMillis())
var calledNoMoreExchanges = false var calledNoMoreExchanges = false
try { try {

View File

@ -21,9 +21,9 @@ import okhttp3.EventListener
import okhttp3.Interceptor import okhttp3.Interceptor
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.Route import okhttp3.Route
import okhttp3.internal.canReuseConnectionFor
import okhttp3.internal.closeQuietly import okhttp3.internal.closeQuietly
import okhttp3.internal.http.ExchangeCodec import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.canReuseConnectionFor
import java.io.IOException import java.io.IOException
import java.net.Socket import java.net.Socket
@ -70,8 +70,8 @@ class ExchangeFinder(
val connectTimeout = chain.connectTimeoutMillis() val connectTimeout = chain.connectTimeoutMillis()
val readTimeout = chain.readTimeoutMillis() val readTimeout = chain.readTimeoutMillis()
val writeTimeout = chain.writeTimeoutMillis() val writeTimeout = chain.writeTimeoutMillis()
val pingIntervalMillis = client.pingIntervalMillis() val pingIntervalMillis = client.pingIntervalMillis
val connectionRetryEnabled = client.retryOnConnectionFailure() val connectionRetryEnabled = client.retryOnConnectionFailure
try { try {
val resultConnection = findHealthyConnection( val resultConnection = findHealthyConnection(

View File

@ -50,14 +50,14 @@ class Transmitter(
private val client: OkHttpClient, private val client: OkHttpClient,
private val call: Call private val call: Call
) { ) {
private val connectionPool: RealConnectionPool = client.connectionPool().delegate private val connectionPool: RealConnectionPool = client.connectionPool.delegate
private val eventListener: EventListener = client.eventListenerFactory().create(call) private val eventListener: EventListener = client.eventListenerFactory.create(call)
private val timeout = object : AsyncTimeout() { private val timeout = object : AsyncTimeout() {
override fun timedOut() { override fun timedOut() {
cancel() cancel()
} }
}.apply { }.apply {
timeout(client.callTimeoutMillis().toLong(), MILLISECONDS) timeout(client.callTimeoutMillis.toLong(), MILLISECONDS)
} }
private var callStackTrace: Any? = null private var callStackTrace: Any? = null
@ -139,14 +139,14 @@ class Transmitter(
var hostnameVerifier: HostnameVerifier? = null var hostnameVerifier: HostnameVerifier? = null
var certificatePinner: CertificatePinner? = null var certificatePinner: CertificatePinner? = null
if (url.isHttps) { if (url.isHttps) {
sslSocketFactory = client.sslSocketFactory() sslSocketFactory = client.sslSocketFactory
hostnameVerifier = client.hostnameVerifier() hostnameVerifier = client.hostnameVerifier
certificatePinner = client.certificatePinner() certificatePinner = client.certificatePinner
} }
return Address(url.host, url.port, client.dns(), client.socketFactory(), return Address(url.host, url.port, client.dns, client.socketFactory,
sslSocketFactory, hostnameVerifier, certificatePinner, client.proxyAuthenticator(), sslSocketFactory, hostnameVerifier, certificatePinner, client.proxyAuthenticator,
client.proxy(), client.protocols(), client.connectionSpecs(), client.proxySelector()) client.proxy, client.protocols, client.connectionSpecs, client.proxySelector)
} }
/** Returns a new exchange to carry a new request and response. */ /** Returns a new exchange to carry a new request and response. */

View File

@ -140,7 +140,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
userRequest: Request userRequest: Request
): Boolean { ): Boolean {
// The application layer has forbidden retries. // The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false if (!client.retryOnConnectionFailure) return false
// We can't send the request body again. // We can't send the request body again.
if (requestSendStarted && requestIsOneShot(e, userRequest)) return false if (requestSendStarted && requestIsOneShot(e, userRequest)) return false
@ -207,10 +207,10 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
if (selectedProxy.type() != Proxy.Type.HTTP) { if (selectedProxy.type() != Proxy.Type.HTTP) {
throw ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy") throw ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy")
} }
return client.proxyAuthenticator().authenticate(route, userResponse) return client.proxyAuthenticator.authenticate(route, userResponse)
} }
HTTP_UNAUTHORIZED -> return client.authenticator().authenticate(route, userResponse) HTTP_UNAUTHORIZED -> return client.authenticator.authenticate(route, userResponse)
HTTP_PERM_REDIRECT, HTTP_TEMP_REDIRECT -> { HTTP_PERM_REDIRECT, HTTP_TEMP_REDIRECT -> {
// "If the 307 or 308 status code is received in response to a request other than GET // "If the 307 or 308 status code is received in response to a request other than GET
@ -229,7 +229,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
// 408's are rare in practice, but some servers like HAProxy use this response code. The // 408's are rare in practice, but some servers like HAProxy use this response code. The
// spec says that we may repeat the request without modifications. Modern browsers also // spec says that we may repeat the request without modifications. Modern browsers also
// repeat the request (even non-idempotent ones.) // repeat the request (even non-idempotent ones.)
if (!client.retryOnConnectionFailure()) { if (!client.retryOnConnectionFailure) {
// The application layer has directed us not to retry the request. // The application layer has directed us not to retry the request.
return null return null
} }
@ -271,7 +271,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
private fun buildRedirectRequest(userResponse: Response, method: String): Request? { private fun buildRedirectRequest(userResponse: Response, method: String): Request? {
// Does the client allow redirects? // Does the client allow redirects?
if (!client.followRedirects()) return null if (!client.followRedirects) return null
val location = userResponse.header("Location") ?: return null val location = userResponse.header("Location") ?: return null
// Don't follow redirects to unsupported protocols. // Don't follow redirects to unsupported protocols.
@ -279,7 +279,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
// If configured, don't follow redirects between SSL and non-SSL. // If configured, don't follow redirects between SSL and non-SSL.
val sameScheme = url.scheme == userResponse.request.url.scheme val sameScheme = url.scheme == userResponse.request.url.scheme
if (!sameScheme && !client.followSslRedirects()) return null if (!sameScheme && !client.followSslRedirects) return null
// Most redirects don't include a request body. // Most redirects don't include a request body.
val requestBuilder = userResponse.request.newBuilder() val requestBuilder = userResponse.request.newBuilder()

View File

@ -460,7 +460,7 @@ class Http1ExchangeCodec(
if (bytesRemainingInChunk == 0L) { if (bytesRemainingInChunk == 0L) {
hasMoreChunks = false hasMoreChunks = false
trailers = readHeaders() trailers = readHeaders()
client!!.cookieJar().receiveHeaders(url, trailers!!) client!!.cookieJar.receiveHeaders(url, trailers!!)
responseBodyComplete() responseBodyComplete()
} }
} }

View File

@ -54,7 +54,7 @@ class Http2ExchangeCodec(
) : ExchangeCodec { ) : ExchangeCodec {
@Volatile private var stream: Http2Stream? = null @Volatile private var stream: Http2Stream? = null
private val protocol: Protocol = if (Protocol.H2_PRIOR_KNOWLEDGE in client.protocols()) { private val protocol: Protocol = if (Protocol.H2_PRIOR_KNOWLEDGE in client.protocols) {
Protocol.H2_PRIOR_KNOWLEDGE Protocol.H2_PRIOR_KNOWLEDGE
} else { } else {
Protocol.HTTP_2 Protocol.HTTP_2

View File

@ -229,4 +229,15 @@ public final class OkHttpClientTest {
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
} }
} }
@Test public void noSslSocketFactoryConfigured() throws Exception {
OkHttpClient client = new OkHttpClient.Builder()
.connectionSpecs(asList(ConnectionSpec.CLEARTEXT))
.build();
try {
client.sslSocketFactory();
fail();
} catch (IllegalStateException expected) {
}
}
} }