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

Spotless code formatter

This commit is contained in:
Yuri Schimke
2019-04-10 21:05:12 +01:00
parent 9e12bc4d60
commit f3949c23bc
32 changed files with 207 additions and 151 deletions

View File

@ -18,6 +18,7 @@ buildscript {
'kotlin': '1.3.20', 'kotlin': '1.3.20',
'moshi': '1.8.0', 'moshi': '1.8.0',
'okio': '2.2.2', 'okio': '2.2.2',
'ktlint': '0.31.0'
] ]
ext.deps = [ ext.deps = [
@ -43,6 +44,7 @@ buildscript {
classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.7.1' classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.7.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:0.9.18" classpath "org.jetbrains.dokka:dokka-gradle-plugin:0.9.18"
classpath 'com.diffplug.spotless:spotless-plugin-gradle:3.21.1'
} }
repositories { repositories {
@ -84,6 +86,7 @@ subprojects { project ->
apply plugin: 'ru.vyarus.animalsniffer' apply plugin: 'ru.vyarus.animalsniffer'
apply plugin: 'net.ltgt.errorprone' apply plugin: 'net.ltgt.errorprone'
apply plugin: 'org.jetbrains.dokka' apply plugin: 'org.jetbrains.dokka'
apply plugin: 'com.diffplug.gradle.spotless'
sourceCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8
@ -104,6 +107,13 @@ subprojects { project ->
signature 'net.sf.androidscents.signature:android-api-level-21:5.0.1_r2@signature' signature 'net.sf.androidscents.signature:android-api-level-21:5.0.1_r2@signature'
signature 'org.codehaus.mojo.signature:java18:1.0@signature' signature 'org.codehaus.mojo.signature:java18:1.0@signature'
} }
spotless {
kotlin {
target "**/*.kt"
ktlint(versions.ktlint).userData(['indent_size': '2', 'continuation_indent_size' : '2'])
}
}
def platform = System.getProperty("okhttp.platform", "jdk8") def platform = System.getProperty("okhttp.platform", "jdk8")

View File

@ -111,8 +111,11 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
} }
private fun buildRequest( private fun buildRequest(
hostname: String, networkRequests: MutableList<Call>, results: MutableList<InetAddress>, hostname: String,
failures: MutableList<Exception>, type: Int networkRequests: MutableList<Call>,
results: MutableList<InetAddress>,
failures: MutableList<Exception>,
type: Int
) { ) {
val request = buildRequest(hostname, type) val request = buildRequest(hostname, type)
val response = getCacheOnlyResponse(request) val response = getCacheOnlyResponse(request)
@ -122,8 +125,10 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
} }
private fun executeRequests( private fun executeRequests(
hostname: String, networkRequests: List<Call>, hostname: String,
responses: MutableList<InetAddress>, failures: MutableList<Exception> networkRequests: List<Call>,
responses: MutableList<InetAddress>,
failures: MutableList<Exception>
) { ) {
val latch = CountDownLatch(networkRequests.size) val latch = CountDownLatch(networkRequests.size)
@ -151,7 +156,9 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
} }
private fun processResponse( private fun processResponse(
response: Response, hostname: String, results: MutableList<InetAddress>, response: Response,
hostname: String,
results: MutableList<InetAddress>,
failures: MutableList<Exception> failures: MutableList<Exception>
) { ) {
try { try {
@ -244,7 +251,6 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
url(requestUrl) url(requestUrl)
} }
}.build() }.build()
class Builder { class Builder {

View File

@ -156,7 +156,8 @@ class HttpLoggingInterceptor @JvmOverloads constructor(
val requestBody = request.body() val requestBody = request.body()
val connection = chain.connection() val connection = chain.connection()
var requestStartMessage = ("--> ${request.method()} ${request.url()}${if (connection != null) " " + connection.protocol() else ""}") var requestStartMessage =
("--> ${request.method()} ${request.url()}${if (connection != null) " " + connection.protocol() else ""}")
if (!logHeaders && requestBody != null) { if (!logHeaders && requestBody != null) {
requestStartMessage += " (${requestBody.contentLength()}-byte body)" requestStartMessage += " (${requestBody.contentLength()}-byte body)"
} }
@ -312,9 +313,9 @@ class HttpLoggingInterceptor @JvmOverloads constructor(
private fun bodyHasUnknownEncoding(headers: Headers): Boolean { private fun bodyHasUnknownEncoding(headers: Headers): Boolean {
val contentEncoding = headers["Content-Encoding"] val contentEncoding = headers["Content-Encoding"]
return (contentEncoding != null return (contentEncoding != null &&
&& !contentEncoding.equals("identity", ignoreCase = true) !contentEncoding.equals("identity", ignoreCase = true) &&
&& !contentEncoding.equals("gzip", ignoreCase = true)) !contentEncoding.equals("gzip", ignoreCase = true))
} }
} }
} }

View File

@ -68,7 +68,10 @@ class LoggingEventListener private constructor(
} }
override fun connectEnd( override fun connectEnd(
call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol? call: Call,
inetSocketAddress: InetSocketAddress,
proxy: Proxy,
protocol: Protocol?
) { ) {
logWithTime("connectEnd: $protocol") logWithTime("connectEnd: $protocol")
} }

View File

@ -22,7 +22,8 @@ import okhttp3.internal.platform.Platform
import org.conscrypt.Conscrypt import org.conscrypt.Conscrypt
import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.not
import org.junit.Assume.* import org.junit.Assume.assumeThat
import org.junit.Assume.assumeTrue
import org.junit.rules.ExternalResource import org.junit.rules.ExternalResource
import java.security.Security import java.security.Security

View File

@ -53,8 +53,8 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
var cookies: MutableList<Cookie>? = null var cookies: MutableList<Cookie>? = null
for ((key, value) in cookieHeaders) { for ((key, value) in cookieHeaders) {
if (("Cookie".equals(key, ignoreCase = true) || "Cookie2".equals(key, ignoreCase = true)) if (("Cookie".equals(key, ignoreCase = true) || "Cookie2".equals(key, ignoreCase = true)) &&
&& value.isNotEmpty()) { value.isNotEmpty()) {
for (header in value) { for (header in value) {
if (cookies == null) cookies = ArrayList() if (cookies == null) cookies = ArrayList()
cookies.addAll(decodeHeaderAsJavaNetCookies(url, header)) cookies.addAll(decodeHeaderAsJavaNetCookies(url, header))

View File

@ -32,18 +32,18 @@ import okhttp3.internal.Util
* HTTP requests that share the same `Address` may also share the same [Connection]. * HTTP requests that share the same `Address` may also share the same [Connection].
*/ */
class Address( class Address(
uriHost: String, uriHost: String,
uriPort: Int, uriPort: Int,
private val dns: Dns, private val dns: Dns,
private val socketFactory: SocketFactory, private val socketFactory: SocketFactory,
private val sslSocketFactory: SSLSocketFactory?, private val sslSocketFactory: SSLSocketFactory?,
private val hostnameVerifier: HostnameVerifier?, private val hostnameVerifier: HostnameVerifier?,
private val certificatePinner: CertificatePinner?, private val certificatePinner: CertificatePinner?,
private val proxyAuthenticator: Authenticator, private val proxyAuthenticator: Authenticator,
private val proxy: Proxy?, private val proxy: Proxy?,
protocols: List<Protocol>, protocols: List<Protocol>,
connectionSpecs: List<ConnectionSpec>, connectionSpecs: List<ConnectionSpec>,
private val proxySelector: ProxySelector private val proxySelector: ProxySelector
) { ) {
private val url: HttpUrl = HttpUrl.Builder() private val url: HttpUrl = HttpUrl.Builder()
.scheme(if (sslSocketFactory != null) "https" else "http") .scheme(if (sslSocketFactory != null) "https" else "http")
@ -104,9 +104,9 @@ class Address(
fun certificatePinner() = certificatePinner fun certificatePinner() = certificatePinner
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
return other is Address return other is Address &&
&& url == other.url url == other.url &&
&& equalsNonHost(other) equalsNonHost(other)
} }
override fun hashCode(): Int { override fun hashCode(): Int {
@ -125,16 +125,16 @@ class Address(
} }
internal fun equalsNonHost(that: Address): Boolean { internal fun equalsNonHost(that: Address): Boolean {
return this.dns == that.dns return this.dns == that.dns &&
&& this.proxyAuthenticator == that.proxyAuthenticator this.proxyAuthenticator == that.proxyAuthenticator &&
&& this.protocols == that.protocols this.protocols == that.protocols &&
&& this.connectionSpecs == that.connectionSpecs this.connectionSpecs == that.connectionSpecs &&
&& this.proxySelector == that.proxySelector this.proxySelector == that.proxySelector &&
&& this.proxy == that.proxy this.proxy == that.proxy &&
&& this.sslSocketFactory == that.sslSocketFactory this.sslSocketFactory == that.sslSocketFactory &&
&& this.hostnameVerifier == that.hostnameVerifier this.hostnameVerifier == that.hostnameVerifier &&
&& this.certificatePinner == that.certificatePinner this.certificatePinner == that.certificatePinner &&
&& this.url().port() == that.url().port() this.url().port() == that.url().port()
} }
override fun toString(): String { override fun toString(): String {

View File

@ -118,7 +118,7 @@ interface Authenticator {
@JvmName("-deprecated_Authenticator") @JvmName("-deprecated_Authenticator")
inline operator fun invoke( inline operator fun invoke(
crossinline block: (route: Route?, response: Response) -> Request? crossinline block: (route: Route?, response: Response) -> Request?
): Authenticator = object: Authenticator { ): Authenticator = object : Authenticator {
override fun authenticate(route: Route?, response: Response) = block(route, response) override fun authenticate(route: Route?, response: Response) = block(route, response)
} }
} }

View File

@ -642,13 +642,12 @@ class Cache internal constructor(
} catch (e: CertificateEncodingException) { } catch (e: CertificateEncodingException) {
throw IOException(e.message) throw IOException(e.message)
} }
} }
fun matches(request: Request, response: Response): Boolean { fun matches(request: Request, response: Response): Boolean {
return url == request.url().toString() return url == request.url().toString() &&
&& requestMethod == request.method() requestMethod == request.method() &&
&& HttpHeaders.varyMatches(response, varyHeaders, request) HttpHeaders.varyMatches(response, varyHeaders, request)
} }
fun response(snapshot: DiskLruCache.Snapshot): Response { fun response(snapshot: DiskLruCache.Snapshot): Response {

View File

@ -279,7 +279,6 @@ class CacheControl private constructor(
pos = HttpHeaders.skipUntil(value, pos, "\"") pos = HttpHeaders.skipUntil(value, pos, "\"")
parameter = value.substring(parameterStart, pos) parameter = value.substring(parameterStart, pos)
pos++ // Consume '"' close quote (if necessary). pos++ // Consume '"' close quote (if necessary).
} else { } else {
// Unquoted string. // Unquoted string.
val parameterStart = pos val parameterStart = pos

View File

@ -154,11 +154,11 @@ data class CertificatePinner internal constructor(
when (pin.hashAlgorithm) { when (pin.hashAlgorithm) {
"sha256/" -> { "sha256/" -> {
if (sha256 == null) sha256 = sha256(x509Certificate) if (sha256 == null) sha256 = sha256(x509Certificate)
if (pin.hash == sha256) return // Success! if (pin.hash == sha256) return // Success!
} }
"sha1/" -> { "sha1/" -> {
if (sha1 == null) sha1 = sha1(x509Certificate) if (sha1 == null) sha1 = sha1(x509Certificate)
if (pin.hash == sha1) return // Success! if (pin.hash == sha1) return // Success!
} }
else -> throw AssertionError("unsupported hashAlgorithm: ${pin.hashAlgorithm}") else -> throw AssertionError("unsupported hashAlgorithm: ${pin.hashAlgorithm}")
} }
@ -235,8 +235,8 @@ data class CertificatePinner internal constructor(
fun matches(hostname: String): Boolean { fun matches(hostname: String): Boolean {
if (pattern.startsWith(WILDCARD)) { if (pattern.startsWith(WILDCARD)) {
val firstDot = hostname.indexOf('.') val firstDot = hostname.indexOf('.')
return hostname.length - firstDot - 1 == canonicalHostname.length return hostname.length - firstDot - 1 == canonicalHostname.length &&
&& hostname.regionMatches(firstDot + 1, canonicalHostname, 0, canonicalHostname.length, hostname.regionMatches(firstDot + 1, canonicalHostname, 0, canonicalHostname.length,
ignoreCase = false) ignoreCase = false)
} }
return hostname == canonicalHostname return hostname == canonicalHostname

View File

@ -71,9 +71,9 @@ class Challenge(
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
return other is Challenge return other is Challenge &&
&& other.scheme == scheme other.scheme == scheme &&
&& other.authParams == authParams other.authParams == authParams
} }
override fun hashCode(): Int { override fun hashCode(): Int {
@ -86,5 +86,4 @@ class Challenge(
override fun toString(): String { override fun toString(): String {
return "$scheme authParams=$authParams" return "$scheme authParams=$authParams"
} }
} }

View File

@ -54,7 +54,7 @@ class CipherSuite private constructor(
* ignoring the "TLS_" or "SSL_" prefix which is not consistent across platforms. In particular * ignoring the "TLS_" or "SSL_" prefix which is not consistent across platforms. In particular
* some IBM JVMs use the "SSL_" prefix everywhere whereas Oracle JVMs mix "TLS_" and "SSL_". * some IBM JVMs use the "SSL_" prefix everywhere whereas Oracle JVMs mix "TLS_" and "SSL_".
*/ */
internal val ORDER_BY_NAME = object: Comparator<String> { internal val ORDER_BY_NAME = object : Comparator<String> {
override fun compare(a: String, b: String): Int { override fun compare(a: String, b: String): Int {
var i = 4 var i = 4
val limit = Math.min(a.length, b.length) val limit = Math.min(a.length, b.length)

View File

@ -125,13 +125,13 @@ class ConnectionSpec internal constructor(builder: Builder) {
return false return false
} }
if (tlsVersions != null if (tlsVersions != null &&
&& !nonEmptyIntersection(Util.NATURAL_ORDER, tlsVersions, socket.enabledProtocols)) { !nonEmptyIntersection(Util.NATURAL_ORDER, tlsVersions, socket.enabledProtocols)) {
return false return false
} }
if (cipherSuites != null if (cipherSuites != null &&
&& !nonEmptyIntersection( !nonEmptyIntersection(
CipherSuite.ORDER_BY_NAME, cipherSuites, socket.enabledCipherSuites)) { CipherSuite.ORDER_BY_NAME, cipherSuites, socket.enabledCipherSuites)) {
return false return false
} }

View File

@ -254,9 +254,9 @@ data class Cookie private constructor(
return true // As in 'example.com' matching 'example.com'. return true // As in 'example.com' matching 'example.com'.
} }
return urlHost.endsWith(domain) return urlHost.endsWith(domain) &&
&& urlHost[urlHost.length - domain.length - 1] == '.' urlHost[urlHost.length - domain.length - 1] == '.' &&
&& !verifyAsIpAddress(urlHost) !verifyAsIpAddress(urlHost)
} }
private fun pathMatch(url: HttpUrl, path: String): Boolean { private fun pathMatch(url: HttpUrl, path: String): Boolean {
@ -381,8 +381,8 @@ data class Cookie private constructor(
} }
// If the domain is a suffix of the url host, it must not be a public suffix. // If the domain is a suffix of the url host, it must not be a public suffix.
if (urlHost.length != domain.length if (urlHost.length != domain.length &&
&& PublicSuffixDatabase.get().getEffectiveTldPlusOne(domain) == null) { PublicSuffixDatabase.get().getEffectiveTldPlusOne(domain) == null) {
return null return null
} }
@ -469,11 +469,11 @@ data class Cookie private constructor(
private fun dateCharacterOffset(input: String, pos: Int, limit: Int, invert: Boolean): Int { private fun dateCharacterOffset(input: String, pos: Int, limit: Int, invert: Boolean): Int {
for (i in pos until limit) { for (i in pos until limit) {
val c = input[i].toInt() val c = input[i].toInt()
val dateCharacter = (c < ' '.toInt() && c != '\t'.toInt() || c >= '\u007f'.toInt() val dateCharacter = (c < ' '.toInt() && c != '\t'.toInt() || c >= '\u007f'.toInt() ||
|| c in '0'.toInt()..'9'.toInt() c in '0'.toInt()..'9'.toInt() ||
|| c in 'a'.toInt()..'z'.toInt() c in 'a'.toInt()..'z'.toInt() ||
|| c in 'A'.toInt()..'Z'.toInt() c in 'A'.toInt()..'Z'.toInt() ||
|| c == ':'.toInt()) c == ':'.toInt())
if (dateCharacter == !invert) return i if (dateCharacter == !invert) return i
} }
return limit return limit

View File

@ -1151,8 +1151,8 @@ class HttpUrl internal constructor(builder: Builder) {
this.scheme = "http" this.scheme = "http"
pos += "http:".length pos += "http:".length
} else { } else {
throw IllegalArgumentException("Expected URL scheme 'http' or 'https' but was '" throw IllegalArgumentException("Expected URL scheme 'http' or 'https' but was '" +
+ input.substring(0, schemeDelimiterOffset) + "'") input.substring(0, schemeDelimiterOffset) + "'")
} }
} else if (base != null) { } else if (base != null) {
this.scheme = base.scheme this.scheme = base.scheme
@ -1297,13 +1297,16 @@ class HttpUrl internal constructor(builder: Builder) {
/** Adds a path segment. If the input is ".." or equivalent, this pops a path segment. */ /** Adds a path segment. If the input is ".." or equivalent, this pops a path segment. */
private fun push( private fun push(
input: String, pos: Int, limit: Int, addTrailingSlash: Boolean, input: String,
pos: Int,
limit: Int,
addTrailingSlash: Boolean,
alreadyEncoded: Boolean alreadyEncoded: Boolean
) { ) {
val segment = canonicalize( val segment = canonicalize(
input, pos, limit, PATH_SEGMENT_ENCODE_SET, alreadyEncoded, false, false, true, null) input, pos, limit, PATH_SEGMENT_ENCODE_SET, alreadyEncoded, false, false, true, null)
if (isDot(segment)) { if (isDot(segment)) {
return // Skip '.' path segments. return // Skip '.' path segments.
} }
if (isDotDot(segment)) { if (isDotDot(segment)) {
pop() pop()
@ -1324,10 +1327,10 @@ class HttpUrl internal constructor(builder: Builder) {
} }
private fun isDotDot(input: String): Boolean { private fun isDotDot(input: String): Boolean {
return (input == ".." return (input == ".." ||
|| input.equals("%2e.", ignoreCase = true) input.equals("%2e.", ignoreCase = true) ||
|| input.equals(".%2e", ignoreCase = true) input.equals(".%2e", ignoreCase = true) ||
|| input.equals("%2e%2e", ignoreCase = true)) input.equals("%2e%2e", ignoreCase = true))
} }
/** /**
@ -1368,12 +1371,12 @@ class HttpUrl internal constructor(builder: Builder) {
for (i in pos + 1 until limit) { for (i in pos + 1 until limit) {
val c = input[i] val c = input[i]
if (c >= 'a' && c <= 'z' if (c >= 'a' && c <= 'z' ||
|| c >= 'A' && c <= 'Z' c >= 'A' && c <= 'Z' ||
|| c >= '0' && c <= '9' c >= '0' && c <= '9' ||
|| c == '+' c == '+' ||
|| c == '-' c == '-' ||
|| c == '.') { c == '.') {
continue // Scheme character. Keep going. continue // Scheme character. Keep going.
} else if (c == ':') { } else if (c == ':') {
return i // Scheme prefix! return i // Scheme prefix!
@ -1436,7 +1439,6 @@ class HttpUrl internal constructor(builder: Builder) {
} catch (e: NumberFormatException) { } catch (e: NumberFormatException) {
return -1 // Invalid port. return -1 // Invalid port.
} }
} }
} }
} }
@ -1615,10 +1617,10 @@ class HttpUrl internal constructor(builder: Builder) {
@JvmStatic @JvmStatic
internal fun percentEncoded(encoded: String, pos: Int, limit: Int): Boolean { internal fun percentEncoded(encoded: String, pos: Int, limit: Int): Boolean {
return (pos + 2 < limit return (pos + 2 < limit &&
&& encoded[pos] == '%' encoded[pos] == '%' &&
&& decodeHexDigit(encoded[pos + 1]) != -1 decodeHexDigit(encoded[pos + 1]) != -1 &&
&& decodeHexDigit(encoded[pos + 2]) != -1) decodeHexDigit(encoded[pos + 2]) != -1)
} }
/** /**
@ -1643,21 +1645,27 @@ class HttpUrl internal constructor(builder: Builder) {
*/ */
@JvmStatic @JvmStatic
internal fun canonicalize( internal fun canonicalize(
input: String, pos: Int, limit: Int, encodeSet: String, input: String,
alreadyEncoded: Boolean, strict: Boolean, plusIsSpace: Boolean, asciiOnly: Boolean, pos: Int,
limit: Int,
encodeSet: String,
alreadyEncoded: Boolean,
strict: Boolean,
plusIsSpace: Boolean,
asciiOnly: Boolean,
charset: Charset? charset: Charset?
): String { ): String {
var codePoint: Int var codePoint: Int
var i = pos var i = pos
while (i < limit) { while (i < limit) {
codePoint = input.codePointAt(i) codePoint = input.codePointAt(i)
if (codePoint < 0x20 if (codePoint < 0x20 ||
|| codePoint == 0x7f codePoint == 0x7f ||
|| codePoint >= 0x80 && asciiOnly codePoint >= 0x80 && asciiOnly ||
|| encodeSet.indexOf(codePoint.toChar()) != -1 encodeSet.indexOf(codePoint.toChar()) != -1 ||
|| codePoint == '%'.toInt() && (!alreadyEncoded || strict && !percentEncoded(input, i, codePoint == '%'.toInt() && (!alreadyEncoded || strict && !percentEncoded(input, i,
limit)) limit)) ||
|| codePoint == '+'.toInt() && plusIsSpace) { codePoint == '+'.toInt() && plusIsSpace) {
// Slow path: the character at i requires encoding! // Slow path: the character at i requires encoding!
val out = Buffer() val out = Buffer()
out.writeUtf8(input, pos, i) out.writeUtf8(input, pos, i)
@ -1674,8 +1682,15 @@ class HttpUrl internal constructor(builder: Builder) {
@JvmStatic @JvmStatic
internal fun canonicalize( internal fun canonicalize(
out: Buffer, input: String, pos: Int, limit: Int, encodeSet: String, out: Buffer,
alreadyEncoded: Boolean, strict: Boolean, plusIsSpace: Boolean, asciiOnly: Boolean, input: String,
pos: Int,
limit: Int,
encodeSet: String,
alreadyEncoded: Boolean,
strict: Boolean,
plusIsSpace: Boolean,
asciiOnly: Boolean,
charset: Charset? charset: Charset?
) { ) {
var encodedCharBuffer: Buffer? = null // Lazily allocated. var encodedCharBuffer: Buffer? = null // Lazily allocated.
@ -1688,11 +1703,11 @@ class HttpUrl internal constructor(builder: Builder) {
} else if (codePoint == '+'.toInt() && plusIsSpace) { } else if (codePoint == '+'.toInt() && plusIsSpace) {
// Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'. // Encode '+' as '%2B' since we permit ' ' to be encoded as either '+' or '%20'.
out.writeUtf8(if (alreadyEncoded) "+" else "%2B") out.writeUtf8(if (alreadyEncoded) "+" else "%2B")
} else if (codePoint < 0x20 } else if (codePoint < 0x20 ||
|| codePoint == 0x7f codePoint == 0x7f ||
|| codePoint >= 0x80 && asciiOnly codePoint >= 0x80 && asciiOnly ||
|| encodeSet.indexOf(codePoint.toChar()) != -1 encodeSet.indexOf(codePoint.toChar()) != -1 ||
|| codePoint == '%'.toInt() && (!alreadyEncoded || strict && !percentEncoded(input, i, codePoint == '%'.toInt() && (!alreadyEncoded || strict && !percentEncoded(input, i,
limit))) { limit))) {
// Percent encode this character. // Percent encode this character.
if (encodedCharBuffer == null) { if (encodedCharBuffer == null) {
@ -1721,15 +1736,24 @@ class HttpUrl internal constructor(builder: Builder) {
@JvmStatic @JvmStatic
internal fun canonicalize( internal fun canonicalize(
input: String, encodeSet: String, alreadyEncoded: Boolean, strict: Boolean, input: String,
plusIsSpace: Boolean, asciiOnly: Boolean, charset: Charset? encodeSet: String,
alreadyEncoded: Boolean,
strict: Boolean,
plusIsSpace: Boolean,
asciiOnly: Boolean,
charset: Charset?
): String = canonicalize(input, 0, input.length, encodeSet, alreadyEncoded, strict, plusIsSpace, ): String = canonicalize(input, 0, input.length, encodeSet, alreadyEncoded, strict, plusIsSpace,
asciiOnly, charset) asciiOnly, charset)
@JvmStatic @JvmStatic
internal fun canonicalize( internal fun canonicalize(
input: String, encodeSet: String, alreadyEncoded: Boolean, strict: Boolean, input: String,
plusIsSpace: Boolean, asciiOnly: Boolean encodeSet: String,
alreadyEncoded: Boolean,
strict: Boolean,
plusIsSpace: Boolean,
asciiOnly: Boolean
): String = canonicalize( ): String = canonicalize(
input, 0, input.length, encodeSet, alreadyEncoded, strict, plusIsSpace, asciiOnly, null) input, 0, input.length, encodeSet, alreadyEncoded, strict, plusIsSpace, asciiOnly, null)
} }

View File

@ -32,7 +32,7 @@ interface Interceptor {
@JvmName("-deprecated_Interceptor") @JvmName("-deprecated_Interceptor")
inline operator fun invoke( inline operator fun invoke(
crossinline block: (chain: Chain) -> Response crossinline block: (chain: Chain) -> Response
): Interceptor = object: Interceptor { ): Interceptor = object : Interceptor {
override fun intercept(chain: Chain) = block(chain) override fun intercept(chain: Chain) = block(chain)
} }
} }

View File

@ -74,7 +74,8 @@ class MultipartBody internal constructor(
*/ */
@Throws(IOException::class) @Throws(IOException::class)
private fun writeOrCountBytes( private fun writeOrCountBytes(
sink: BufferedSink?, countBytes: Boolean sink: BufferedSink?,
countBytes: Boolean
): Long { ): Long {
var sink = sink var sink = sink
var byteCount = 0L var byteCount = 0L

View File

@ -586,7 +586,8 @@ open class OkHttpClient internal constructor(
* ``` * ```
*/ */
fun sslSocketFactory( fun sslSocketFactory(
sslSocketFactory: SSLSocketFactory, trustManager: X509TrustManager sslSocketFactory: SSLSocketFactory,
trustManager: X509TrustManager
) = apply { ) = apply {
this.sslSocketFactory = sslSocketFactory this.sslSocketFactory = sslSocketFactory
this.certificateChainCleaner = CertificateChainCleaner.get(trustManager) this.certificateChainCleaner = CertificateChainCleaner.get(trustManager)

View File

@ -154,9 +154,9 @@ internal class RealCall private constructor(
* sensitive information. * sensitive information.
*/ */
fun toLoggableString(): String { fun toLoggableString(): String {
return ((if (isCanceled()) "canceled " else "") return ((if (isCanceled()) "canceled " else "") +
+ (if (forWebSocket) "web socket" else "call") (if (forWebSocket) "web socket" else "call") +
+ " to " + redactedUrl()) " to " + redactedUrl())
} }
fun redactedUrl(): String = originalRequest.url().redact() fun redactedUrl(): String = originalRequest.url().redact()

View File

@ -90,7 +90,7 @@ class Response internal constructor(
*/ */
fun handshake(): Handshake? = handshake fun handshake(): Handshake? = handshake
fun headers(name: String): List<String> = headers.values(name) fun headers(name: String): List<String> = headers.values(name)
@JvmOverloads @JvmOverloads
fun header(name: String, defaultValue: String? = null): String? = headers[name] ?: defaultValue fun header(name: String, defaultValue: String? = null): String? = headers[name] ?: defaultValue

View File

@ -23,8 +23,8 @@ enum class TlsVersion(private val javaName: String) {
TLS_1_3("TLSv1.3"), // 2016. TLS_1_3("TLSv1.3"), // 2016.
TLS_1_2("TLSv1.2"), // 2008. TLS_1_2("TLSv1.2"), // 2008.
TLS_1_1("TLSv1.1"), // 2006. TLS_1_1("TLSv1.1"), // 2006.
TLS_1_0("TLSv1"), // 1999. TLS_1_0("TLSv1"), // 1999.
SSL_3_0("SSLv3"); // 1996. SSL_3_0("SSLv3"); // 1996.
fun javaName() = javaName fun javaName() = javaName

View File

@ -21,7 +21,7 @@ import okio.Sink
import java.io.IOException import java.io.IOException
/** A sink that never throws IOExceptions, even if the underlying sink does. */ /** A sink that never throws IOExceptions, even if the underlying sink does. */
internal open class FaultHidingSink(delegate: Sink): ForwardingSink(delegate) { internal open class FaultHidingSink(delegate: Sink) : ForwardingSink(delegate) {
private var hasErrors = false private var hasErrors = false
override fun write(source: Buffer, byteCount: Long) { override fun write(source: Buffer, byteCount: Long) {

View File

@ -15,7 +15,7 @@
*/ */
package okhttp3.internal.connection package okhttp3.internal.connection
import java.io.IOException; import java.io.IOException
/** /**
* An exception thrown to indicate a problem connecting via a single Route. Multiple attempts may * An exception thrown to indicate a problem connecting via a single Route. Multiple attempts may

View File

@ -17,18 +17,18 @@ package okhttp3.internal.http
object HttpMethod { object HttpMethod {
@JvmStatic @JvmStatic
fun invalidatesCache(method: String): Boolean = (method == "POST" fun invalidatesCache(method: String): Boolean = (method == "POST" ||
|| method == "PATCH" method == "PATCH" ||
|| method == "PUT" method == "PUT" ||
|| method == "DELETE" method == "DELETE" ||
|| method == "MOVE") // WebDAV method == "MOVE") // WebDAV
@JvmStatic @JvmStatic
fun requiresRequestBody(method: String): Boolean = (method == "POST" fun requiresRequestBody(method: String): Boolean = (method == "POST" ||
|| method == "PUT" method == "PUT" ||
|| method == "PATCH" method == "PATCH" ||
|| method == "PROPPATCH" // WebDAV method == "PROPPATCH" || // WebDAV
|| method == "REPORT") // CalDAV/CardDAV (defined in WebDAV Versioning) method == "REPORT") // CalDAV/CardDAV (defined in WebDAV Versioning)
@JvmStatic @JvmStatic
fun permitsRequestBody(method: String): Boolean = !(method == "GET" || method == "HEAD") fun permitsRequestBody(method: String): Boolean = !(method == "GET" || method == "HEAD")

View File

@ -43,7 +43,7 @@ class RealInterceptorChain(
private val connectTimeout: Int, private val connectTimeout: Int,
private val readTimeout: Int, private val readTimeout: Int,
private val writeTimeout: Int private val writeTimeout: Int
): Interceptor.Chain { ) : Interceptor.Chain {
private var calls: Int = 0 private var calls: Int = 0
@ -98,14 +98,14 @@ class RealInterceptorChain(
// If we already have a stream, confirm that the incoming request will use it. // If we already have a stream, confirm that the incoming request will use it.
if (this.exchange != null && !this.exchange.connection().supportsUrl(request.url())) { if (this.exchange != null && !this.exchange.connection().supportsUrl(request.url())) {
throw IllegalStateException("network interceptor " + interceptors[index - 1] throw IllegalStateException("network interceptor " + interceptors[index - 1] +
+ " must retain the same host and port") " must retain the same host and port")
} }
// If we already have a stream, confirm that this is the only call to chain.proceed(). // If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.exchange != null && calls > 1) { if (this.exchange != null && calls > 1) {
throw IllegalStateException("network interceptor " + interceptors[index - 1] throw IllegalStateException("network interceptor " + interceptors[index - 1] +
+ " must call proceed() exactly once") " must call proceed() exactly once")
} }
// Call the next interceptor in the chain. // Call the next interceptor in the chain.
@ -116,8 +116,8 @@ class RealInterceptorChain(
// Confirm that the next interceptor made its required call to chain.proceed(). // Confirm that the next interceptor made its required call to chain.proceed().
if (exchange != null && index + 1 < interceptors.size && next.calls != 1) { if (exchange != null && index + 1 < interceptors.size && next.calls != 1) {
throw IllegalStateException("network interceptor " + interceptor throw IllegalStateException("network interceptor " + interceptor +
+ " must call proceed() exactly once") " must call proceed() exactly once")
} }
// Confirm that the intercepted response isn't null. // Confirm that the intercepted response isn't null.

View File

@ -75,7 +75,8 @@ class AndroidPlatform(
@Throws(IOException::class) @Throws(IOException::class)
override fun connectSocket( override fun connectSocket(
socket: Socket, address: InetSocketAddress, socket: Socket,
address: InetSocketAddress,
connectTimeout: Int connectTimeout: Int
) { ) {
try { try {
@ -118,10 +119,12 @@ class AndroidPlatform(
} }
override fun configureTlsExtensions( override fun configureTlsExtensions(
sslSocket: SSLSocket, hostname: String?, protocols: List<Protocol> sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) { ) {
if (!sslSocketClass.isInstance(sslSocket)) { if (!sslSocketClass.isInstance(sslSocket)) {
return // No TLS extensions if the socket class is custom. return // No TLS extensions if the socket class is custom.
} }
try { try {
// Enable SNI and session tickets. // Enable SNI and session tickets.
@ -206,7 +209,8 @@ class AndroidPlatform(
@Throws(InvocationTargetException::class, IllegalAccessException::class) @Throws(InvocationTargetException::class, IllegalAccessException::class)
private fun api24IsCleartextTrafficPermitted( private fun api24IsCleartextTrafficPermitted(
hostname: String, networkPolicyClass: Class<*>, hostname: String,
networkPolicyClass: Class<*>,
networkSecurityPolicy: Any networkSecurityPolicy: Any
): Boolean = try { ): Boolean = try {
val isCleartextTrafficPermittedMethod = networkPolicyClass val isCleartextTrafficPermittedMethod = networkPolicyClass
@ -218,7 +222,8 @@ class AndroidPlatform(
@Throws(InvocationTargetException::class, IllegalAccessException::class) @Throws(InvocationTargetException::class, IllegalAccessException::class)
private fun api23IsCleartextTrafficPermitted( private fun api23IsCleartextTrafficPermitted(
hostname: String, networkPolicyClass: Class<*>, hostname: String,
networkPolicyClass: Class<*>,
networkSecurityPolicy: Any networkSecurityPolicy: Any
): Boolean = try { ): Boolean = try {
val isCleartextTrafficPermittedMethod = networkPolicyClass val isCleartextTrafficPermittedMethod = networkPolicyClass
@ -264,7 +269,7 @@ class AndroidPlatform(
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
@Throws(SSLPeerUnverifiedException::class) @Throws(SSLPeerUnverifiedException::class)
override// Reflection on List<Certificate>. override // Reflection on List<Certificate>.
fun clean(chain: List<Certificate>, hostname: String): List<Certificate> = try { fun clean(chain: List<Certificate>, hostname: String): List<Certificate> = try {
val certificates = (chain as List<X509Certificate>).toTypedArray() val certificates = (chain as List<X509Certificate>).toTypedArray()
checkServerTrusted.invoke( checkServerTrusted.invoke(

View File

@ -66,7 +66,9 @@ class ConscryptPlatform private constructor() : Platform() {
} }
override fun configureTlsExtensions( override fun configureTlsExtensions(
sslSocket: SSLSocket, hostname: String?, protocols: List<Protocol> sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) { ) {
if (Conscrypt.isConscrypt(sslSocket)) { if (Conscrypt.isConscrypt(sslSocket)) {
// Enable SNI and session tickets. // Enable SNI and session tickets.

View File

@ -24,11 +24,16 @@ import javax.net.ssl.SSLSocket
/** OpenJDK 8 with `org.mortbay.jetty.alpn:alpn-boot` in the boot class path. */ /** OpenJDK 8 with `org.mortbay.jetty.alpn:alpn-boot` in the boot class path. */
class Jdk8WithJettyBootPlatform( class Jdk8WithJettyBootPlatform(
private val putMethod: Method, private val getMethod: Method, private val removeMethod: Method, private val putMethod: Method,
private val clientProviderClass: Class<*>, private val serverProviderClass: Class<*> private val getMethod: Method,
private val removeMethod: Method,
private val clientProviderClass: Class<*>,
private val serverProviderClass: Class<*>
) : Platform() { ) : Platform() {
override fun configureTlsExtensions( override fun configureTlsExtensions(
sslSocket: SSLSocket, hostname: String?, protocols: List<Protocol> sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) { ) {
val names = alpnProtocolNames(protocols) val names = alpnProtocolNames(protocols)
@ -51,7 +56,6 @@ class Jdk8WithJettyBootPlatform(
} catch (e: InvocationTargetException) { } catch (e: InvocationTargetException) {
throw AssertionError("failed to remove ALPN", e) throw AssertionError("failed to remove ALPN", e)
} }
} }
override fun getSelectedProtocol(socket: SSLSocket): String? { override fun getSelectedProtocol(socket: SSLSocket): String? {
@ -96,8 +100,8 @@ class Jdk8WithJettyBootPlatform(
return null return null
} else if (methodName == "protocols" && callArgs.isEmpty()) { } else if (methodName == "protocols" && callArgs.isEmpty()) {
return protocols // Client advertises these protocols. return protocols // Client advertises these protocols.
} else if ((methodName == "selectProtocol" || methodName == "select") } else if ((methodName == "selectProtocol" || methodName == "select") &&
&& String::class.java == returnType && callArgs.size == 1 && callArgs[0] is List<*>) { String::class.java == returnType && callArgs.size == 1 && callArgs[0] is List<*>) {
val peerProtocols = callArgs[0] as List<*> val peerProtocols = callArgs[0] as List<*>
// Pick the first known protocol the peer advertises. // Pick the first known protocol the peer advertises.
for (i in 0..peerProtocols.size) { for (i in 0..peerProtocols.size) {

View File

@ -29,7 +29,8 @@ class Jdk9Platform(
@JvmField val getProtocolMethod: Method @JvmField val getProtocolMethod: Method
) : Platform() { ) : Platform() {
override fun configureTlsExtensions( override fun configureTlsExtensions(
sslSocket: SSLSocket, hostname: String?, sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol> protocols: List<Protocol>
) { ) {
try { try {

View File

@ -176,7 +176,7 @@ open class Platform {
override fun toString(): String = javaClass.simpleName override fun toString(): String = javaClass.simpleName
companion object { companion object {
private @Volatile var platform = findPlatform() @Volatile private var platform = findPlatform()
const val INFO = 4 const val INFO = 4
const val WARN = 5 const val WARN = 5

View File

@ -33,7 +33,7 @@ import javax.net.ssl.SSLPeerUnverifiedException
*/ */
class BasicCertificateChainCleaner( class BasicCertificateChainCleaner(
private val trustRootIndex: TrustRootIndex private val trustRootIndex: TrustRootIndex
): CertificateChainCleaner() { ) : CertificateChainCleaner() {
/** /**
* Returns a cleaned chain for [chain]. * Returns a cleaned chain for [chain].