From 7ad4f970ba81e179aed4be4c4774399e14838cc3 Mon Sep 17 00:00:00 2001 From: Masaru Nomura Date: Thu, 23 May 2019 23:12:19 -0400 Subject: [PATCH] Idiomatic Kotlin for Response.kt - define `@get:JvmName(...)` for the following vals in constructor instead of passing `builder: Builder`. - `request: Request` - `protocol: Protocol` - `message: String` - `code: Int` - `handshake: Handshake?` - `headers: Headers` - `body: ResponseBody?` - `networkResponse: Response?` - `cacheResponse: Response?` - `priorResponse: Response?` - `sentRequestAtMillis: Long` - `receivedResponseAtMillis: Long` - `exchange: Exchange?` - add `@Deprecated(...)` to the following functions. - `fun request(): Request` - `fun protocol(): Protocol` - `fun message(): String` - `fun code(): Int` - `fun handshake(): Handshake?` - `fun headers(): Headers` - `fun body(): ResponseBody?` - `fun networkResponse(): Response?` - `fun cacheResponse(): Response?` - `fun priorResponse(): Response?` - `fun sentRequestAtMillis(): Long` - `fun receivedResponseAtMillis(): Long` - `fun cacheControl(): CacheControl` - clean up code where `()`(parentheses) is unnecessarily used. --- okcurl/src/main/java/okhttp3/curl/Main.kt | 6 +- .../java/okhttp3/dnsoverhttps/DnsOverHttps.kt | 10 +- .../okhttp3/logging/HttpLoggingInterceptor.kt | 8 +- .../okhttp3/internal/sse/RealEventSource.kt | 2 +- .../src/main/java/okhttp3/sse/EventSources.kt | 2 +- .../main/java/okhttp3/JavaNetAuthenticator.kt | 4 +- okhttp/src/main/java/okhttp3/Cache.kt | 38 +-- okhttp/src/main/java/okhttp3/Response.kt | 224 +++++++++++++----- .../internal/cache/CacheInterceptor.kt | 22 +- .../okhttp3/internal/cache/CacheStrategy.kt | 26 +- .../internal/connection/RealConnection.kt | 4 +- .../internal/http/BridgeInterceptor.kt | 6 +- .../internal/http/CallServerInterceptor.kt | 10 +- .../java/okhttp3/internal/http/HttpHeaders.kt | 4 +- .../internal/http/RealInterceptorChain.kt | 2 +- .../http/RetryAndFollowUpInterceptor.kt | 30 +-- .../java/okhttp3/internal/http/StatusLine.kt | 2 +- .../internal/http1/Http1ExchangeCodec.kt | 2 +- .../java/okhttp3/internal/ws/RealWebSocket.kt | 4 +- okhttp/src/test/java/okhttp3/ConscryptTest.kt | 8 +- .../okhttp3/KotlinSourceCompatibilityTest.kt | 26 +- 21 files changed, 267 insertions(+), 173 deletions(-) diff --git a/okcurl/src/main/java/okhttp3/curl/Main.kt b/okcurl/src/main/java/okhttp3/curl/Main.kt index 154c73b6c..71a89aa0f 100644 --- a/okcurl/src/main/java/okhttp3/curl/Main.kt +++ b/okcurl/src/main/java/okhttp3/curl/Main.kt @@ -130,7 +130,7 @@ class Main : Runnable { val response = client.newCall(request).execute() if (showHeaders) { println(StatusLine.get(response)) - val headers = response.headers() + val headers = response.headers for ((name, value) in headers) { println("$name: $value") } @@ -139,13 +139,13 @@ class Main : Runnable { // Stream the response to the System.out as it is returned from the server. val out = System.out.sink() - val source = response.body()!!.source() + val source = response.body!!.source() while (!source.exhausted()) { out.write(source.buffer, source.buffer.size) out.flush() } - response.body()!!.close() + response.body!!.close() } catch (e: IOException) { e.printStackTrace() } finally { diff --git a/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.kt b/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.kt index cd336ca2d..55928968b 100644 --- a/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.kt +++ b/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.kt @@ -202,7 +202,7 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns { val cacheResponse = client.newCall(cacheRequest).execute() - if (cacheResponse.code() != 504) { + if (cacheResponse.code != 504) { return cacheResponse } } catch (ioe: IOException) { @@ -216,16 +216,16 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns { @Throws(Exception::class) private fun readResponse(hostname: String, response: Response): List { - if (response.cacheResponse() == null && response.protocol() !== Protocol.HTTP_2) { - Platform.get().log(Platform.WARN, "Incorrect protocol: ${response.protocol()}", null) + if (response.cacheResponse == null && response.protocol !== Protocol.HTTP_2) { + Platform.get().log(Platform.WARN, "Incorrect protocol: ${response.protocol}", null) } response.use { if (!response.isSuccessful) { - throw IOException("response: " + response.code() + " " + response.message()) + throw IOException("response: " + response.code + " " + response.message) } - val body = response.body() + val body = response.body if (body!!.contentLength() > MAX_RESPONSE_SIZE) { throw IOException( diff --git a/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.kt b/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.kt index 4e607aa08..94b222bd6 100644 --- a/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.kt +++ b/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.kt @@ -223,21 +223,21 @@ class HttpLoggingInterceptor @JvmOverloads constructor( val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs) - val responseBody = response.body()!! + val responseBody = response.body!! val contentLength = responseBody.contentLength() val bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length" logger.log( - "<-- ${response.code()}${if (response.message().isEmpty()) "" else ' ' + response.message()} ${response.request().url} (${tookMs}ms${if (!logHeaders) ", $bodySize body" else ""})") + "<-- ${response.code}${if (response.message.isEmpty()) "" else ' ' + response.message} ${response.request.url} (${tookMs}ms${if (!logHeaders) ", $bodySize body" else ""})") if (logHeaders) { - val headers = response.headers() + val headers = response.headers for (i in 0 until headers.size) { logHeader(headers, i) } if (!logBody || !response.promisesBody()) { logger.log("<-- END HTTP") - } else if (bodyHasUnknownEncoding(response.headers())) { + } else if (bodyHasUnknownEncoding(response.headers)) { logger.log("<-- END HTTP (encoded body omitted)") } else { val source = responseBody.source() diff --git a/okhttp-sse/src/main/java/okhttp3/internal/sse/RealEventSource.kt b/okhttp-sse/src/main/java/okhttp3/internal/sse/RealEventSource.kt index f24a669a2..1d72013c2 100644 --- a/okhttp-sse/src/main/java/okhttp3/internal/sse/RealEventSource.kt +++ b/okhttp-sse/src/main/java/okhttp3/internal/sse/RealEventSource.kt @@ -53,7 +53,7 @@ class RealEventSource( return } - val body = response.body()!! + val body = response.body!! if (!body.isEventStream()) { listener.onFailure(this, diff --git a/okhttp-sse/src/main/java/okhttp3/sse/EventSources.kt b/okhttp-sse/src/main/java/okhttp3/sse/EventSources.kt index 2702cd365..e7297a500 100644 --- a/okhttp-sse/src/main/java/okhttp3/sse/EventSources.kt +++ b/okhttp-sse/src/main/java/okhttp3/sse/EventSources.kt @@ -34,7 +34,7 @@ object EventSources { @JvmStatic fun processResponse(response: Response, listener: EventSourceListener) { - val eventSource = RealEventSource(response.request(), listener) + val eventSource = RealEventSource(response.request, listener) eventSource.processResponse(response) } } diff --git a/okhttp-urlconnection/src/main/java/okhttp3/JavaNetAuthenticator.kt b/okhttp-urlconnection/src/main/java/okhttp3/JavaNetAuthenticator.kt index 6dfd8f768..edeba0846 100644 --- a/okhttp-urlconnection/src/main/java/okhttp3/JavaNetAuthenticator.kt +++ b/okhttp-urlconnection/src/main/java/okhttp3/JavaNetAuthenticator.kt @@ -29,9 +29,9 @@ class JavaNetAuthenticator : okhttp3.Authenticator { @Throws(IOException::class) override fun authenticate(route: Route?, response: Response): Request? { val challenges = response.challenges() - val request = response.request() + val request = response.request val url = request.url - val proxyAuthorization = response.code() == 407 + val proxyAuthorization = response.code == 407 val proxy = route?.proxy ?: Proxy.NO_PROXY for (challenge in challenges) { diff --git a/okhttp/src/main/java/okhttp3/Cache.kt b/okhttp/src/main/java/okhttp3/Cache.kt index 8048429cd..63bb0fe1f 100644 --- a/okhttp/src/main/java/okhttp3/Cache.kt +++ b/okhttp/src/main/java/okhttp3/Cache.kt @@ -174,7 +174,7 @@ class Cache internal constructor( val response = entry.response(snapshot) if (!entry.matches(request, response)) { - response.body()?.closeQuietly() + response.body?.closeQuietly() return null } @@ -182,11 +182,11 @@ class Cache internal constructor( } internal fun put(response: Response): CacheRequest? { - val requestMethod = response.request().method + val requestMethod = response.request.method - if (HttpMethod.invalidatesCache(response.request().method)) { + if (HttpMethod.invalidatesCache(response.request.method)) { try { - remove(response.request()) + remove(response.request) } catch (_: IOException) { // The cache cannot be written. } @@ -206,7 +206,7 @@ class Cache internal constructor( val entry = Entry(response) var editor: DiskLruCache.Editor? = null try { - editor = cache.edit(key(response.request().url)) ?: return null + editor = cache.edit(key(response.request.url)) ?: return null entry.writeTo(editor) return RealCacheRequest(editor) } catch (_: IOException) { @@ -222,7 +222,7 @@ class Cache internal constructor( internal fun update(cached: Response, network: Response) { val entry = Entry(network) - val snapshot = (cached.body() as CacheResponseBody).snapshot + val snapshot = (cached.body as CacheResponseBody).snapshot var editor: DiskLruCache.Editor? = null try { editor = snapshot.edit() // Returns null if snapshot is not current. @@ -537,16 +537,16 @@ class Cache internal constructor( } internal constructor(response: Response) { - this.url = response.request().url.toString() + this.url = response.request.url.toString() this.varyHeaders = response.varyHeaders() - this.requestMethod = response.request().method - this.protocol = response.protocol() - this.code = response.code() - this.message = response.message() - this.responseHeaders = response.headers() - this.handshake = response.handshake() - this.sentRequestMillis = response.sentRequestAtMillis() - this.receivedResponseMillis = response.receivedResponseAtMillis() + this.requestMethod = response.request.method + this.protocol = response.protocol + this.code = response.code + this.message = response.message + this.responseHeaders = response.headers + this.handshake = response.handshake + this.sentRequestMillis = response.sentRequestAtMillis + this.receivedResponseMillis = response.receivedResponseAtMillis } @Throws(IOException::class) @@ -724,13 +724,13 @@ class Cache internal constructor( cachedRequest: Headers, newRequest: Request ): Boolean { - return cachedResponse.headers().varyFields().none { + return cachedResponse.headers.varyFields().none { cachedRequest.values(it) != newRequest.headers(it) } } /** Returns true if a Vary header contains an asterisk. Such responses cannot be cached. */ - fun Response.hasVaryAll() = "*" in headers().varyFields() + fun Response.hasVaryAll() = "*" in headers.varyFields() /** * Returns the names of the request headers that need to be checked for equality when caching. @@ -759,8 +759,8 @@ class Cache internal constructor( fun Response.varyHeaders(): Headers { // Use the request headers sent over the network, since that's what the response varies on. // Otherwise OkHttp-supplied headers like "Accept-Encoding: gzip" may be lost. - val requestHeaders = networkResponse()!!.request().headers - val responseHeaders = headers() + val requestHeaders = networkResponse!!.request.headers + val responseHeaders = headers return varyHeaders(requestHeaders, responseHeaders) } diff --git a/okhttp/src/main/java/okhttp3/Response.kt b/okhttp/src/main/java/okhttp3/Response.kt index 1ce5a3f52..08e2f58f6 100644 --- a/okhttp/src/main/java/okhttp3/Response.kt +++ b/okhttp/src/main/java/okhttp3/Response.kt @@ -37,25 +37,6 @@ import java.net.HttpURLConnection.HTTP_UNAUTHORIZED * [ResponseBody] for an explanation and examples. */ class Response internal constructor( - internal val request: Request, - internal val protocol: Protocol, - internal val message: String, - builder: Builder -) : Closeable { - internal val code: Int = builder.code - internal val handshake: Handshake? = builder.handshake - internal val headers: Headers = builder.headers.build() - internal val body: ResponseBody? = builder.body - internal val networkResponse: Response? = builder.networkResponse - internal val cacheResponse: Response? = builder.cacheResponse - internal val priorResponse: Response? = builder.priorResponse - internal val sentRequestAtMillis: Long = builder.sentRequestAtMillis - internal val receivedResponseAtMillis: Long = builder.receivedResponseAtMillis - internal val exchange: Exchange? = builder.exchange - - @Volatile - private var cacheControl: CacheControl? = null // Lazily initialized. - /** * The wire-level request that initiated this HTTP response. This is not necessarily the same * request issued by the application: @@ -65,12 +46,96 @@ class Response internal constructor( * * It may be the request generated in response to an HTTP redirect or authentication * challenge. In this case the request URL may be different than the initial request URL. */ - fun request(): Request = request + @get:JvmName("request") val request: Request, /** Returns the HTTP protocol, such as [Protocol.HTTP_1_1] or [Protocol.HTTP_1_0]. */ - fun protocol(): Protocol = protocol + @get:JvmName("protocol") val protocol: Protocol, + + /** Returns the HTTP status message. */ + @get:JvmName("message") val message: String, /** Returns the HTTP status code. */ + @get:JvmName("code") val code: Int, + + /** + * Returns the TLS handshake of the connection that carried this response, or null if the + * response was received without TLS. + */ + @get:JvmName("handshake") val handshake: Handshake?, + + /** Returns the HTTP headers. */ + @get:JvmName("headers") val headers: Headers, + + /** + * Returns a non-null value if this response was passed to [Callback.onResponse] or returned + * from [Call.execute]. Response bodies must be [closed][ResponseBody] and may + * be consumed only once. + * + * This always returns null on responses returned from [cacheResponse], [networkResponse], + * and [priorResponse]. + */ + @get:JvmName("body") val body: ResponseBody?, + + /** + * Returns the raw response received from the network. Will be null if this response didn't use + * the network, such as when the response is fully cached. The body of the returned response + * should not be read. + */ + @get:JvmName("networkResponse") val networkResponse: Response?, + + /** + * Returns the raw response received from the cache. Will be null if this response didn't use + * the cache. For conditional get requests the cache response and network response may both be + * non-null. The body of the returned response should not be read. + */ + @get:JvmName("cacheResponse") val cacheResponse: Response?, + + /** + * Returns the response for the HTTP redirect or authorization challenge that triggered this + * response, or null if this response wasn't triggered by an automatic retry. The body of the + * returned response should not be read because it has already been consumed by the redirecting + * client. + */ + @get:JvmName("priorResponse") val priorResponse: Response?, + + /** + * Returns a [timestamp][System.currentTimeMillis] taken immediately before OkHttp + * transmitted the initiating request over the network. If this response is being served from the + * cache then this is the timestamp of the original request. + */ + @get:JvmName("sentRequestAtMillis") val sentRequestAtMillis: Long, + + /** + * Returns a [timestamp][System.currentTimeMillis] taken immediately after OkHttp + * received this response's headers from the network. If this response is being served from the + * cache then this is the timestamp of the original response. + */ + @get:JvmName("receivedResponseAtMillis") val receivedResponseAtMillis: Long, + + @get:JvmName("exchange") val exchange: Exchange? +) : Closeable { + + private var lazyCacheControl: CacheControl? = null + + @JvmName("-deprecated_request") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "request"), + level = DeprecationLevel.WARNING) + fun request(): Request = request + + @JvmName("-deprecated_protocol") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "protocol"), + level = DeprecationLevel.WARNING) + fun protocol(): Protocol = protocol + + @JvmName("-deprecated_code") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "code"), + level = DeprecationLevel.WARNING) fun code(): Int = code /** @@ -80,13 +145,18 @@ class Response internal constructor( val isSuccessful: Boolean get() = code in 200..299 - /** Returns the HTTP status message. */ + @JvmName("-deprecated_message") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "message"), + level = DeprecationLevel.WARNING) fun message(): String = message - /** - * Returns the TLS handshake of the connection that carried this response, or null if the - * response was received without TLS. - */ + @JvmName("-deprecated_handshake") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "handshake"), + level = DeprecationLevel.WARNING) fun handshake(): Handshake? = handshake fun headers(name: String): List = headers.values(name) @@ -94,6 +164,11 @@ class Response internal constructor( @JvmOverloads fun header(name: String, defaultValue: String? = null): String? = headers[name] ?: defaultValue + @JvmName("-deprecated_headers") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "headers"), + level = DeprecationLevel.WARNING) fun headers(): Headers = headers /** @@ -123,14 +198,11 @@ class Response internal constructor( return ResponseBody.create(body.contentType(), buffer.size, buffer) } - /** - * Returns a non-null value if this response was passed to [Callback.onResponse] or returned - * from [Call.execute]. Response bodies must be [closed][ResponseBody] and may - * be consumed only once. - * - * This always returns null on responses returned from [cacheResponse], [networkResponse], - * and [priorResponse]. - */ + @JvmName("-deprecated_body") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "body"), + level = DeprecationLevel.WARNING) fun body(): ResponseBody? = body fun newBuilder(): Builder = Builder(this) @@ -142,26 +214,25 @@ class Response internal constructor( else -> false } - /** - * Returns the raw response received from the network. Will be null if this response didn't use - * the network, such as when the response is fully cached. The body of the returned response - * should not be read. - */ + @JvmName("-deprecated_networkResponse") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "networkResponse"), + level = DeprecationLevel.WARNING) fun networkResponse(): Response? = networkResponse - /** - * Returns the raw response received from the cache. Will be null if this response didn't use - * the cache. For conditional get requests the cache response and network response may both be - * non-null. The body of the returned response should not be read. - */ + @JvmName("-deprecated_cacheResponse") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "cacheResponse"), + level = DeprecationLevel.WARNING) fun cacheResponse(): Response? = cacheResponse - /** - * Returns the response for the HTTP redirect or authorization challenge that triggered this - * response, or null if this response wasn't triggered by an automatic retry. The body of the - * returned response should not be read because it has already been consumed by the redirecting - * client. - */ + @JvmName("-deprecated_priorResponse") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "priorResponse"), + level = DeprecationLevel.WARNING) fun priorResponse(): Response? = priorResponse /** @@ -176,7 +247,7 @@ class Response internal constructor( * auth param, this is up to the caller that interprets these challenges. */ fun challenges(): List { - return headers().parseChallenges( + return headers.parseChallenges( when (code) { HTTP_UNAUTHORIZED -> "WWW-Authenticate" HTTP_PROXY_AUTH -> "Proxy-Authenticate" @@ -189,22 +260,35 @@ class Response internal constructor( * Returns the cache control directives for this response. This is never null, even if this * response contains no `Cache-Control` header. */ - fun cacheControl(): CacheControl = cacheControl ?: CacheControl.parse(headers).also { - cacheControl = it - } + @get:JvmName("cacheControl") val cacheControl: CacheControl + get() { + var result = lazyCacheControl + if (result == null) { + result = CacheControl.parse(headers) + lazyCacheControl = result + } + return result + } - /** - * Returns a [timestamp][System.currentTimeMillis] taken immediately before OkHttp - * transmitted the initiating request over the network. If this response is being served from the - * cache then this is the timestamp of the original request. - */ + @JvmName("-deprecated_cacheControl") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "cacheControl"), + level = DeprecationLevel.WARNING) + fun cacheControl(): CacheControl = cacheControl + + @JvmName("-deprecated_sentRequestAtMillis") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "sentRequestAtMillis"), + level = DeprecationLevel.WARNING) fun sentRequestAtMillis(): Long = sentRequestAtMillis - /** - * Returns a [timestamp][System.currentTimeMillis] taken immediately after OkHttp - * received this response's headers from the network. If this response is being served from the - * cache then this is the timestamp of the original response. - */ + @JvmName("-deprecated_receivedResponseAtMillis") + @Deprecated( + message = "moved to val", + replaceWith = ReplaceWith(expression = "receivedResponseAtMillis"), + level = DeprecationLevel.WARNING) fun receivedResponseAtMillis(): Long = receivedResponseAtMillis /** @@ -353,7 +437,17 @@ class Response internal constructor( checkNotNull(request) { "request == null" }, checkNotNull(protocol) { "protocol == null" }, checkNotNull(message) { "message == null" }, - this) + code, + handshake, + headers.build(), + body, + networkResponse, + cacheResponse, + priorResponse, + sentRequestAtMillis, + receivedResponseAtMillis, + exchange + ) } } } diff --git a/okhttp/src/main/java/okhttp3/internal/cache/CacheInterceptor.kt b/okhttp/src/main/java/okhttp3/internal/cache/CacheInterceptor.kt index 157bbac5c..e5fe1ff58 100644 --- a/okhttp/src/main/java/okhttp3/internal/cache/CacheInterceptor.kt +++ b/okhttp/src/main/java/okhttp3/internal/cache/CacheInterceptor.kt @@ -54,7 +54,7 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { if (cacheCandidate != null && cacheResponse == null) { // The cache candidate wasn't applicable. Close it. - cacheCandidate.body()?.closeQuietly() + cacheCandidate.body?.closeQuietly() } // If we're forbidden from using the network and the cache is insufficient, fail. @@ -83,22 +83,22 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { } finally { // If we're crashing on I/O or otherwise, don't leak the cache body. if (networkResponse == null && cacheCandidate != null) { - cacheCandidate.body()?.closeQuietly() + cacheCandidate.body?.closeQuietly() } } // If we have a cache response too, then we're doing a conditional get. if (cacheResponse != null) { - if (networkResponse?.code() == HTTP_NOT_MODIFIED) { + if (networkResponse?.code == HTTP_NOT_MODIFIED) { val response = cacheResponse.newBuilder() - .headers(combine(cacheResponse.headers(), networkResponse.headers())) - .sentRequestAtMillis(networkResponse.sentRequestAtMillis()) - .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis()) + .headers(combine(cacheResponse.headers, networkResponse.headers)) + .sentRequestAtMillis(networkResponse.sentRequestAtMillis) + .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis) .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build() - networkResponse.body()!!.close() + networkResponse.body!!.close() // Update the cache after combining headers but before stripping the // Content-Encoding header (as performed by initContentStream()). @@ -106,7 +106,7 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { cache.update(cacheResponse, response) return response } else { - cacheResponse.body()?.closeQuietly() + cacheResponse.body?.closeQuietly() } } @@ -145,7 +145,7 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { if (cacheRequest == null) return response val cacheBodyUnbuffered = cacheRequest.body() - val source = response.body()!!.source() + val source = response.body!!.source() val cacheBody = cacheBodyUnbuffered.buffer() val cacheWritingSource = object : Source { @@ -193,7 +193,7 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { } val contentType = response.header("Content-Type") - val contentLength = response.body()!!.contentLength() + val contentLength = response.body!!.contentLength() return response.newBuilder() .body(RealResponseBody(contentType, contentLength, cacheWritingSource.buffer())) .build() @@ -202,7 +202,7 @@ class CacheInterceptor(internal val cache: Cache?) : Interceptor { companion object { private fun stripBody(response: Response?): Response? { - return if (response?.body() != null) { + return if (response?.body != null) { response.newBuilder().body(null).build() } else { response diff --git a/okhttp/src/main/java/okhttp3/internal/cache/CacheStrategy.kt b/okhttp/src/main/java/okhttp3/internal/cache/CacheStrategy.kt index b2ba36de0..5ad6f4e32 100644 --- a/okhttp/src/main/java/okhttp3/internal/cache/CacheStrategy.kt +++ b/okhttp/src/main/java/okhttp3/internal/cache/CacheStrategy.kt @@ -91,14 +91,14 @@ class CacheStrategy internal constructor( * cached response older than 24 hours, we are required to attach a warning. */ private fun isFreshnessLifetimeHeuristic(): Boolean { - return cacheResponse!!.cacheControl().maxAgeSeconds == -1 && expires == null + return cacheResponse!!.cacheControl.maxAgeSeconds == -1 && expires == null } init { if (cacheResponse != null) { - this.sentRequestMillis = cacheResponse.sentRequestAtMillis() - this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis() - val headers = cacheResponse.headers() + this.sentRequestMillis = cacheResponse.sentRequestAtMillis + this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis + val headers = cacheResponse.headers for (i in 0 until headers.size) { val fieldName = headers.name(i) val value = headers.value(i) @@ -145,7 +145,7 @@ class CacheStrategy internal constructor( } // Drop the cached response if it's missing a required handshake. - if (request.isHttps && cacheResponse.handshake() == null) { + if (request.isHttps && cacheResponse.handshake == null) { return CacheStrategy(request, null) } @@ -161,7 +161,7 @@ class CacheStrategy internal constructor( return CacheStrategy(request, null) } - val responseCaching = cacheResponse.cacheControl() + val responseCaching = cacheResponse.cacheControl val ageMillis = cacheResponseAge() var freshMillis = computeFreshnessLifetime() @@ -229,7 +229,7 @@ class CacheStrategy internal constructor( * date. */ private fun computeFreshnessLifetime(): Long { - val responseCaching = cacheResponse!!.cacheControl() + val responseCaching = cacheResponse!!.cacheControl if (responseCaching.maxAgeSeconds != -1) { return SECONDS.toMillis(responseCaching.maxAgeSeconds.toLong()) } @@ -241,7 +241,7 @@ class CacheStrategy internal constructor( return if (delta > 0L) delta else 0L } - if (lastModified != null && cacheResponse.request().url.query == null) { + if (lastModified != null && cacheResponse.request.url.query == null) { // As recommended by the HTTP RFC and implemented in Firefox, the max age of a document // should be defaulted to 10% of the document's age at the time it was served. Default // expiration dates aren't used for URIs containing a query. @@ -290,7 +290,7 @@ class CacheStrategy internal constructor( fun isCacheable(response: Response, request: Request): Boolean { // Always go to network for uncacheable response codes (RFC 7231 section 6.1), This // implementation doesn't support caching partial content. - when (response.code()) { + when (response.code) { HTTP_OK, HTTP_NOT_AUTHORITATIVE, HTTP_NO_CONTENT, @@ -311,9 +311,9 @@ class CacheStrategy internal constructor( // http://tools.ietf.org/html/rfc7234#section-3 // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage. if (response.header("Expires") == null && - response.cacheControl().maxAgeSeconds == -1 && - !response.cacheControl().isPublic && - !response.cacheControl().isPrivate) { + response.cacheControl.maxAgeSeconds == -1 && + !response.cacheControl.isPublic && + !response.cacheControl.isPrivate) { return false } } @@ -325,7 +325,7 @@ class CacheStrategy internal constructor( } // A 'no-store' directive on request or response prevents the response from being cached. - return !response.cacheControl().noStore && !request.cacheControl.noStore + return !response.cacheControl.noStore && !request.cacheControl.noStore } } } diff --git a/okhttp/src/main/java/okhttp3/internal/connection/RealConnection.kt b/okhttp/src/main/java/okhttp3/internal/connection/RealConnection.kt index 5e887e599..e1ededfb6 100644 --- a/okhttp/src/main/java/okhttp3/internal/connection/RealConnection.kt +++ b/okhttp/src/main/java/okhttp3/internal/connection/RealConnection.kt @@ -423,7 +423,7 @@ class RealConnection( .build() tunnelCodec.skipConnectBody(response) - when (response.code()) { + when (response.code) { HTTP_OK -> { // Assume the server won't send a TLS ServerHello until we send a TLS ClientHello. If // that happens, then we will have buffered bytes that are needed by the SSLSocket! @@ -444,7 +444,7 @@ class RealConnection( } } - else -> throw IOException("Unexpected response code for CONNECT: ${response.code()}") + else -> throw IOException("Unexpected response code for CONNECT: ${response.code}") } } } diff --git a/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.kt b/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.kt index df3a1dadd..caf6957ab 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/BridgeInterceptor.kt @@ -83,7 +83,7 @@ class BridgeInterceptor(private val cookieJar: CookieJar) : Interceptor { val networkResponse = chain.proceed(requestBuilder.build()) - cookieJar.receiveHeaders(userRequest.url, networkResponse.headers()) + cookieJar.receiveHeaders(userRequest.url, networkResponse.headers) val responseBuilder = networkResponse.newBuilder() .request(userRequest) @@ -91,10 +91,10 @@ class BridgeInterceptor(private val cookieJar: CookieJar) : Interceptor { if (transparentGzip && "gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) && networkResponse.promisesBody()) { - val responseBody = networkResponse.body() + val responseBody = networkResponse.body if (responseBody != null) { val gzipSource = GzipSource(responseBody.source()) - val strippedHeaders = networkResponse.headers().newBuilder() + val strippedHeaders = networkResponse.headers.newBuilder() .removeAll("Content-Encoding") .removeAll("Content-Length") .build() diff --git a/okhttp/src/main/java/okhttp3/internal/http/CallServerInterceptor.kt b/okhttp/src/main/java/okhttp3/internal/http/CallServerInterceptor.kt index fe1caba39..474970e88 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/CallServerInterceptor.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/CallServerInterceptor.kt @@ -87,7 +87,7 @@ class CallServerInterceptor(private val forWebSocket: Boolean) : Interceptor { .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(System.currentTimeMillis()) .build() - var code = response.code() + var code = response.code if (code == 100) { // server sent a 100-continue even though we did not request one. // try again to read the actual response @@ -97,7 +97,7 @@ class CallServerInterceptor(private val forWebSocket: Boolean) : Interceptor { .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(System.currentTimeMillis()) .build() - code = response.code() + code = response.code } exchange.responseHeadersEnd(response) @@ -112,13 +112,13 @@ class CallServerInterceptor(private val forWebSocket: Boolean) : Interceptor { .body(exchange.openResponseBody(response)) .build() } - if ("close".equals(response.request().header("Connection"), ignoreCase = true) || + if ("close".equals(response.request.header("Connection"), ignoreCase = true) || "close".equals(response.header("Connection"), ignoreCase = true)) { exchange.noNewExchangesOnConnection() } - if ((code == 204 || code == 205) && response.body()?.contentLength() ?: -1L > 0L) { + if ((code == 204 || code == 205) && response.body?.contentLength() ?: -1L > 0L) { throw ProtocolException( - "HTTP $code had non-zero Content-Length: ${response.body()?.contentLength()}") + "HTTP $code had non-zero Content-Length: ${response.body?.contentLength()}") } return response } diff --git a/okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.kt b/okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.kt index b15f8ed44..5f1b787c8 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/HttpHeaders.kt @@ -212,11 +212,11 @@ fun CookieJar.receiveHeaders(url: HttpUrl, headers: Headers) { */ fun Response.promisesBody(): Boolean { // HEAD requests never yield a body regardless of the response headers. - if (request().method == "HEAD") { + if (request.method == "HEAD") { return false } - val responseCode = code() + val responseCode = code if ((responseCode < HTTP_CONTINUE || responseCode >= 200) && responseCode != HTTP_NO_CONTENT && responseCode != HTTP_NOT_MODIFIED) { diff --git a/okhttp/src/main/java/okhttp3/internal/http/RealInterceptorChain.kt b/okhttp/src/main/java/okhttp3/internal/http/RealInterceptorChain.kt index 8c87d4b74..157324d66 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RealInterceptorChain.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/RealInterceptorChain.kt @@ -117,7 +117,7 @@ class RealInterceptorChain( "network interceptor $interceptor must call proceed() exactly once" } - check(response.body() != null) { "interceptor $interceptor returned a response with no body" } + check(response.body != null) { "interceptor $interceptor returned a response with no body" } return response } diff --git a/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt b/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt index ff5748fa7..0833c54f1 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt @@ -113,7 +113,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto return response } - response.body()?.closeQuietly() + response.body?.closeQuietly() if (transmitter.hasExchange()) { exchange?.detachWithViolence() } @@ -198,9 +198,9 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto */ @Throws(IOException::class) private fun followUpRequest(userResponse: Response, route: Route?): Request? { - val responseCode = userResponse.code() + val responseCode = userResponse.code - val method = userResponse.request().method + val method = userResponse.request.method when (responseCode) { HTTP_PROXY_AUTH -> { val selectedProxy = route!!.proxy @@ -234,12 +234,12 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto return null } - val requestBody = userResponse.request().body + val requestBody = userResponse.request.body if (requestBody != null && requestBody.isOneShot()) { return null } - val priorResponse = userResponse.priorResponse() - if (priorResponse != null && priorResponse.code() == HTTP_CLIENT_TIMEOUT) { + val priorResponse = userResponse.priorResponse + if (priorResponse != null && priorResponse.code == HTTP_CLIENT_TIMEOUT) { // We attempted to retry and got another timeout. Give up. return null } @@ -248,19 +248,19 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto return null } - return userResponse.request() + return userResponse.request } HTTP_UNAVAILABLE -> { - val priorResponse = userResponse.priorResponse() - if (priorResponse != null && priorResponse.code() == HTTP_UNAVAILABLE) { + val priorResponse = userResponse.priorResponse + if (priorResponse != null && priorResponse.code == HTTP_UNAVAILABLE) { // We attempted to retry and got another timeout. Give up. return null } if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) { // specifically received an instruction to retry without delay - return userResponse.request() + return userResponse.request } return null @@ -275,20 +275,20 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto val location = userResponse.header("Location") ?: return null // Don't follow redirects to unsupported protocols. - val url = userResponse.request().url.resolve(location) ?: return null + val url = userResponse.request.url.resolve(location) ?: return null // 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 // Most redirects don't include a request body. - val requestBuilder = userResponse.request().newBuilder() + val requestBuilder = userResponse.request.newBuilder() if (HttpMethod.permitsRequestBody(method)) { val maintainBody = HttpMethod.redirectsWithBody(method) if (HttpMethod.redirectsToGet(method)) { requestBuilder.method("GET", null) } else { - val requestBody = if (maintainBody) userResponse.request().body else null + val requestBody = if (maintainBody) userResponse.request.body else null requestBuilder.method(method, requestBody) } if (!maintainBody) { @@ -301,7 +301,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto // When redirecting across hosts, drop all authentication headers. This // is potentially annoying to the application layer since they have no // way to retain them. - if (!userResponse.request().url.canReuseConnectionFor(url)) { + if (!userResponse.request.url.canReuseConnectionFor(url)) { requestBuilder.removeHeader("Authorization") } diff --git a/okhttp/src/main/java/okhttp3/internal/http/StatusLine.kt b/okhttp/src/main/java/okhttp3/internal/http/StatusLine.kt index 8c2d073d5..73679d04f 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/StatusLine.kt +++ b/okhttp/src/main/java/okhttp3/internal/http/StatusLine.kt @@ -46,7 +46,7 @@ class StatusLine( const val HTTP_CONTINUE = 100 fun get(response: Response): StatusLine { - return StatusLine(response.protocol(), response.code(), response.message()) + return StatusLine(response.protocol, response.code, response.message) } @Throws(IOException::class) diff --git a/okhttp/src/main/java/okhttp3/internal/http1/Http1ExchangeCodec.kt b/okhttp/src/main/java/okhttp3/internal/http1/Http1ExchangeCodec.kt index db790b456..bfe46a659 100644 --- a/okhttp/src/main/java/okhttp3/internal/http1/Http1ExchangeCodec.kt +++ b/okhttp/src/main/java/okhttp3/internal/http1/Http1ExchangeCodec.kt @@ -133,7 +133,7 @@ class Http1ExchangeCodec( override fun openResponseBodySource(response: Response): Source { return when { !response.promisesBody() -> newFixedLengthSource(0) - response.isChunked() -> newChunkedSource(response.request().url) + response.isChunked() -> newChunkedSource(response.request.url) else -> { val contentLength = response.headersContentLength() if (contentLength != -1L) { diff --git a/okhttp/src/main/java/okhttp3/internal/ws/RealWebSocket.kt b/okhttp/src/main/java/okhttp3/internal/ws/RealWebSocket.kt index 5730485b3..47179ff9d 100644 --- a/okhttp/src/main/java/okhttp3/internal/ws/RealWebSocket.kt +++ b/okhttp/src/main/java/okhttp3/internal/ws/RealWebSocket.kt @@ -192,9 +192,9 @@ class RealWebSocket( @Throws(IOException::class) internal fun checkUpgradeSuccess(response: Response, exchange: Exchange?) { - if (response.code() != 101) { + if (response.code != 101) { throw ProtocolException( - "Expected HTTP 101 response but was '${response.code()} ${response.message()}'") + "Expected HTTP 101 response but was '${response.code} ${response.message}'") } val headerConnection = response.header("Connection") diff --git a/okhttp/src/test/java/okhttp3/ConscryptTest.kt b/okhttp/src/test/java/okhttp3/ConscryptTest.kt index b2d4164aa..48c88978d 100644 --- a/okhttp/src/test/java/okhttp3/ConscryptTest.kt +++ b/okhttp/src/test/java/okhttp3/ConscryptTest.kt @@ -64,8 +64,8 @@ class ConscryptTest { val response = client.newCall(request).execute() - assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2) - assertThat(response.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3) + assertThat(response.protocol).isEqualTo(Protocol.HTTP_2) + assertThat(response.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3) } @Test @@ -76,8 +76,8 @@ class ConscryptTest { val response = client.newCall(request).execute() - assertThat(response.protocol()).isEqualTo(Protocol.HTTP_2) - if (response.handshake()!!.tlsVersion != TlsVersion.TLS_1_3) { + assertThat(response.protocol).isEqualTo(Protocol.HTTP_2) + if (response.handshake!!.tlsVersion != TlsVersion.TLS_1_3) { System.err.println("Flaky TLSv1.3 with google") // assertThat(response.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3) } diff --git a/okhttp/src/test/java/okhttp3/KotlinSourceCompatibilityTest.kt b/okhttp/src/test/java/okhttp3/KotlinSourceCompatibilityTest.kt index 059c9d7bf..be8b3c089 100644 --- a/okhttp/src/test/java/okhttp3/KotlinSourceCompatibilityTest.kt +++ b/okhttp/src/test/java/okhttp3/KotlinSourceCompatibilityTest.kt @@ -1041,27 +1041,27 @@ class KotlinSourceCompatibilityTest { @Test @Ignore fun response() { val response: Response = Response.Builder().build() - val request: Request = response.request() - val protocol: Protocol = response.protocol() - val code: Int = response.code() + val request: Request = response.request + val protocol: Protocol = response.protocol + val code: Int = response.code val successful: Boolean = response.isSuccessful - val message: String = response.message() - val handshake: Handshake? = response.handshake() + val message: String = response.message + val handshake: Handshake? = response.handshake val headersForName: List = response.headers("") val header: String? = response.header("") - val headers: Headers = response.headers() + val headers: Headers = response.headers val trailers: Headers = response.trailers() val peekBody: ResponseBody = response.peekBody(0L) - val body: ResponseBody? = response.body() + val body: ResponseBody? = response.body val builder: Response.Builder = response.newBuilder() val redirect: Boolean = response.isRedirect - val networkResponse: Response? = response.networkResponse() - val cacheResponse: Response? = response.cacheResponse() - val priorResponse: Response? = response.priorResponse() + val networkResponse: Response? = response.networkResponse + val cacheResponse: Response? = response.cacheResponse + val priorResponse: Response? = response.priorResponse val challenges: List = response.challenges() - val cacheControl: CacheControl = response.cacheControl() - val sentRequestAtMillis: Long = response.sentRequestAtMillis() - val receivedResponseAtMillis: Long = response.receivedResponseAtMillis() + val cacheControl: CacheControl = response.cacheControl + val sentRequestAtMillis: Long = response.sentRequestAtMillis + val receivedResponseAtMillis: Long = response.receivedResponseAtMillis } @Test @Ignore