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

Adopt HttpUrl's new Kotlin API

This commit is contained in:
Jesse Wilson
2019-05-20 21:01:04 -04:00
parent f4655995ca
commit e67ec3c51e
18 changed files with 64 additions and 64 deletions

View File

@ -1019,7 +1019,7 @@ class MockWebServer : ExternalResource(), Closeable {
) { ) {
for (pushPromise in promises) { for (pushPromise in promises) {
val pushedHeaders = mutableListOf<Header>() val pushedHeaders = mutableListOf<Header>()
pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host())) pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host))
pushedHeaders.add(Header(Header.TARGET_METHOD, pushPromise.method)) pushedHeaders.add(Header(Header.TARGET_METHOD, pushPromise.method))
pushedHeaders.add(Header(Header.TARGET_PATH, pushPromise.path)) pushedHeaders.add(Header(Header.TARGET_PATH, pushPromise.path))
val pushPromiseHeaders = pushPromise.headers val pushPromiseHeaders = pushPromise.headers

View File

@ -309,7 +309,7 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
val hosts = builder.bootstrapDnsHosts val hosts = builder.bootstrapDnsHosts
return if (hosts != null) { return if (hosts != null) {
BootstrapDns(builder.url!!.host(), hosts) BootstrapDns(builder.url!!.host, hosts)
} else { } else {
builder.systemDns builder.systemDns
} }

View File

@ -45,21 +45,21 @@ class JavaNetAuthenticator : okhttp3.Authenticator {
proxyAddress.hostName, proxyAddress.hostName,
proxy.connectToInetAddress(url), proxy.connectToInetAddress(url),
proxyAddress.port, proxyAddress.port,
url.scheme(), url.scheme,
challenge.realm, challenge.realm,
challenge.scheme, challenge.scheme,
url.url(), url.toUrl(),
Authenticator.RequestorType.PROXY Authenticator.RequestorType.PROXY
) )
} else { } else {
Authenticator.requestPasswordAuthentication( Authenticator.requestPasswordAuthentication(
url.host(), url.host,
proxy.connectToInetAddress(url), proxy.connectToInetAddress(url),
url.port(), url.port,
url.scheme(), url.scheme,
challenge.realm, challenge.realm,
challenge.scheme, challenge.scheme,
url.url(), url.toUrl(),
Authenticator.RequestorType.SERVER Authenticator.RequestorType.SERVER
) )
} }
@ -80,7 +80,7 @@ class JavaNetAuthenticator : okhttp3.Authenticator {
@Throws(IOException::class) @Throws(IOException::class)
private fun Proxy.connectToInetAddress(url: HttpUrl): InetAddress { private fun Proxy.connectToInetAddress(url: HttpUrl): InetAddress {
return when { return when {
type() == Proxy.Type.DIRECT -> InetAddress.getByName(url.host()) type() == Proxy.Type.DIRECT -> InetAddress.getByName(url.host)
else -> (address() as InetSocketAddress).address else -> (address() as InetSocketAddress).address
} }
} }

View File

@ -36,7 +36,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
} }
val multimap = mapOf("Set-Cookie" to cookieStrings) val multimap = mapOf("Set-Cookie" to cookieStrings)
try { try {
cookieHandler.put(url.uri(), multimap) cookieHandler.put(url.toUri(), multimap)
} catch (e: IOException) { } catch (e: IOException) {
Platform.get().log(WARN, "Saving cookies failed for " + url.resolve("/...")!!, e) Platform.get().log(WARN, "Saving cookies failed for " + url.resolve("/...")!!, e)
} }
@ -45,7 +45,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
override fun loadForRequest(url: HttpUrl): List<Cookie> { override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookieHeaders = try { val cookieHeaders = try {
// The RI passes all headers. We don't have 'em, so we don't pass 'em! // The RI passes all headers. We don't have 'em, so we don't pass 'em!
cookieHandler.get(url.uri(), emptyMap<String, List<String>>()) cookieHandler.get(url.toUri(), emptyMap<String, List<String>>())
} catch (e: IOException) { } catch (e: IOException) {
Platform.get().log(WARN, "Loading cookies failed for " + url.resolve("/...")!!, e) Platform.get().log(WARN, "Loading cookies failed for " + url.resolve("/...")!!, e)
return emptyList() return emptyList()
@ -102,7 +102,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
result.add(Cookie.Builder() result.add(Cookie.Builder()
.name(name) .name(name)
.value(value) .value(value)
.domain(url.host()) .domain(url.host)
.build()) .build())
pos = pairEnd + 1 pos = pairEnd + 1
} }

View File

@ -194,12 +194,12 @@ class Address(
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 {
return "Address{" + return "Address{" +
"${url.host()}:${url.port()}, " + "${url.host}:${url.port}, " +
(if (proxy != null) "proxy=$proxy" else "proxySelector=$proxySelector") + (if (proxy != null) "proxy=$proxy" else "proxySelector=$proxySelector") +
"}" "}"
} }

View File

@ -292,10 +292,10 @@ data class CertificatePinner internal constructor(
internal fun newPin(pattern: String, pin: String): Pin { internal fun newPin(pattern: String, pin: String): Pin {
val canonicalHostname = when { val canonicalHostname = when {
pattern.startsWith(WILDCARD) -> { pattern.startsWith(WILDCARD) -> {
HttpUrl.get("http://${pattern.substring(WILDCARD.length)}").host() HttpUrl.get("http://${pattern.substring(WILDCARD.length)}").host
} }
else -> { else -> {
HttpUrl.get("http://$pattern").host() HttpUrl.get("http://$pattern").host
} }
} }

View File

@ -99,9 +99,9 @@ data class Cookie private constructor(
*/ */
fun matches(url: HttpUrl): Boolean { fun matches(url: HttpUrl): Boolean {
val domainMatch = if (hostOnly) { val domainMatch = if (hostOnly) {
url.host() == domain url.host == domain
} else { } else {
domainMatch(url.host(), domain) domainMatch(url.host, domain)
} }
if (!domainMatch) return false if (!domainMatch) return false
@ -313,7 +313,7 @@ data class Cookie private constructor(
} }
private fun pathMatch(url: HttpUrl, path: String): Boolean { private fun pathMatch(url: HttpUrl, path: String): Boolean {
val urlPath = url.encodedPath() val urlPath = url.encodedPath
if (urlPath == path) { if (urlPath == path) {
return true // As in '/foo' matching '/foo'. return true // As in '/foo' matching '/foo'.
@ -426,7 +426,7 @@ data class Cookie private constructor(
} }
// If the domain is present, it must domain match. Otherwise we have a host-only cookie. // If the domain is present, it must domain match. Otherwise we have a host-only cookie.
val urlHost = url.host() val urlHost = url.host
if (domain == null) { if (domain == null) {
domain = urlHost domain = urlHost
} else if (!domainMatch(urlHost, domain)) { } else if (!domainMatch(urlHost, domain)) {
@ -442,7 +442,7 @@ data class Cookie private constructor(
// If the path is absent or didn't start with '/', use the default path. It's a string like // If the path is absent or didn't start with '/', use the default path. It's a string like
// '/foo/bar' for a URL like 'http://example.com/foo/bar/baz'. It always starts with '/'. // '/foo/bar' for a URL like 'http://example.com/foo/bar/baz'. It always starts with '/'.
if (path == null || !path.startsWith("/")) { if (path == null || !path.startsWith("/")) {
val encodedPath = url.encodedPath() val encodedPath = url.encodedPath
val lastSlash = encodedPath.lastIndexOf('/') val lastSlash = encodedPath.lastIndexOf('/')
path = if (lastSlash != 0) encodedPath.substring(0, lastSlash) else "/" path = if (lastSlash != 0) encodedPath.substring(0, lastSlash) else "/"
} }

View File

@ -738,15 +738,15 @@ class HttpUrl internal constructor(
fun newBuilder(): Builder { fun newBuilder(): Builder {
val result = Builder() val result = Builder()
result.scheme = scheme result.scheme = scheme
result.encodedUsername = encodedUsername() result.encodedUsername = encodedUsername
result.encodedPassword = encodedPassword() result.encodedPassword = encodedPassword
result.host = host result.host = host
// If we're set to a default port, unset it in case of a scheme change. // If we're set to a default port, unset it in case of a scheme change.
result.port = if (port != defaultPort(scheme)) port else -1 result.port = if (port != defaultPort(scheme)) port else -1
result.encodedPathSegments.clear() result.encodedPathSegments.clear()
result.encodedPathSegments.addAll(encodedPathSegments()) result.encodedPathSegments.addAll(encodedPathSegments)
result.encodedQuery(encodedQuery()) result.encodedQuery(encodedQuery)
result.encodedFragment = encodedFragment() result.encodedFragment = encodedFragment
return result return result
} }
@ -1365,14 +1365,14 @@ class HttpUrl internal constructor(
} }
} else { } else {
// This is a relative link. Copy over all authority components. Also maybe the path & query. // This is a relative link. Copy over all authority components. Also maybe the path & query.
this.encodedUsername = base.encodedUsername() this.encodedUsername = base.encodedUsername
this.encodedPassword = base.encodedPassword() this.encodedPassword = base.encodedPassword
this.host = base.host this.host = base.host
this.port = base.port this.port = base.port
this.encodedPathSegments.clear() this.encodedPathSegments.clear()
this.encodedPathSegments.addAll(base.encodedPathSegments()) this.encodedPathSegments.addAll(base.encodedPathSegments)
if (pos == limit || input[pos] == '#') { if (pos == limit || input[pos] == '#') {
encodedQuery(base.encodedQuery()) encodedQuery(base.encodedQuery)
} }
} }

View File

@ -101,7 +101,7 @@ internal class RealCall private constructor(
this.callsPerHost = other.callsPerHost this.callsPerHost = other.callsPerHost
} }
fun host(): String = originalRequest.url().host() fun host(): String = originalRequest.url().host
fun request(): Request = originalRequest fun request(): Request = originalRequest

View File

@ -139,13 +139,13 @@ fun nonEmptyIntersection(
} }
fun hostHeader(url: HttpUrl, includeDefaultPort: Boolean): String { fun hostHeader(url: HttpUrl, includeDefaultPort: Boolean): String {
val host = if (":" in url.host()) { val host = if (":" in url.host) {
"[${url.host()}]" "[${url.host}]"
} else { } else {
url.host() url.host
} }
return if (includeDefaultPort || url.port() != HttpUrl.defaultPort(url.scheme())) { return if (includeDefaultPort || url.port != HttpUrl.defaultPort(url.scheme)) {
"$host:${url.port()}" "$host:${url.port}"
} else { } else {
host host
} }
@ -288,9 +288,9 @@ fun toHeaderBlock(headers: Headers): List<Header> = (0 until headers.size).map {
} }
/** Returns true if an HTTP request for [a] and [b] can reuse a connection. */ /** Returns true if an HTTP request for [a] and [b] can reuse a connection. */
fun sameConnection(a: HttpUrl, b: HttpUrl): Boolean = (a.host() == b.host() && fun sameConnection(a: HttpUrl, b: HttpUrl): Boolean = (a.host == b.host &&
a.port() == b.port() && a.port == b.port &&
a.scheme() == b.scheme()) a.scheme == b.scheme)
fun eventListenerFactory(listener: EventListener): EventListener.Factory = fun eventListenerFactory(listener: EventListener): EventListener.Factory =
EventListener.Factory { listener } EventListener.Factory { listener }

View File

@ -242,7 +242,7 @@ class CacheStrategy internal constructor(
return if (delta > 0L) delta else 0L 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 // 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 // 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. // expiration dates aren't used for URIs containing a query.

View File

@ -152,7 +152,7 @@ class RealConnection(
throw RouteException(UnknownServiceException( throw RouteException(UnknownServiceException(
"CLEARTEXT communication not enabled for client")) "CLEARTEXT communication not enabled for client"))
} }
val host = route.address().url.host() val host = route.address().url.host
if (!Platform.get().isCleartextTrafficPermitted(host)) { if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw RouteException(UnknownServiceException( throw RouteException(UnknownServiceException(
"CLEARTEXT communication to $host not permitted by network security policy")) "CLEARTEXT communication to $host not permitted by network security policy"))
@ -322,7 +322,7 @@ class RealConnection(
val sink = this.sink!! val sink = this.sink!!
socket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream. socket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream.
val http2Connection = Http2Connection.Builder(true) val http2Connection = Http2Connection.Builder(true)
.socket(socket, route.address().url.host(), source, sink) .socket(socket, route.address().url.host, source, sink)
.listener(this) .listener(this)
.pingIntervalMillis(pingIntervalMillis) .pingIntervalMillis(pingIntervalMillis)
.build() .build()
@ -339,12 +339,12 @@ class RealConnection(
try { try {
// Create the wrapper over the connected socket. // Create the wrapper over the connected socket.
sslSocket = sslSocketFactory!!.createSocket( sslSocket = sslSocketFactory!!.createSocket(
rawSocket, address.url.host(), address.url.port(), true /* autoClose */) as SSLSocket rawSocket, address.url.host, address.url.port, true /* autoClose */) as SSLSocket
// Configure the socket's ciphers, TLS versions, and extensions. // Configure the socket's ciphers, TLS versions, and extensions.
val connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket) val connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket)
if (connectionSpec.supportsTlsExtensions()) { if (connectionSpec.supportsTlsExtensions()) {
Platform.get().configureTlsExtensions(sslSocket, address.url.host(), address.protocols) Platform.get().configureTlsExtensions(sslSocket, address.url.host, address.protocols)
} }
// Force handshake. This can throw! // Force handshake. This can throw!
@ -354,24 +354,24 @@ class RealConnection(
val unverifiedHandshake = sslSocketSession.handshake() val unverifiedHandshake = sslSocketSession.handshake()
// Verify that the socket's certificates are acceptable for the target host. // Verify that the socket's certificates are acceptable for the target host.
if (!address.hostnameVerifier!!.verify(address.url.host(), sslSocketSession)) { if (!address.hostnameVerifier!!.verify(address.url.host, sslSocketSession)) {
val peerCertificates = unverifiedHandshake.peerCertificates val peerCertificates = unverifiedHandshake.peerCertificates
if (peerCertificates.isNotEmpty()) { if (peerCertificates.isNotEmpty()) {
val cert = peerCertificates[0] as X509Certificate val cert = peerCertificates[0] as X509Certificate
throw SSLPeerUnverifiedException(""" throw SSLPeerUnverifiedException("""
|Hostname ${address.url.host()} not verified: |Hostname ${address.url.host} not verified:
| certificate: ${CertificatePinner.pin(cert)} | certificate: ${CertificatePinner.pin(cert)}
| DN: ${cert.subjectDN.name} | DN: ${cert.subjectDN.name}
| subjectAltNames: ${OkHostnameVerifier.allSubjectAltNames(cert)} | subjectAltNames: ${OkHostnameVerifier.allSubjectAltNames(cert)}
""".trimMargin()) """.trimMargin())
} else { } else {
throw SSLPeerUnverifiedException( throw SSLPeerUnverifiedException(
"Hostname ${address.url.host()} not verified (no certificates)") "Hostname ${address.url.host} not verified (no certificates)")
} }
} }
// Check that the certificate pinner is satisfied by the certificates presented. // Check that the certificate pinner is satisfied by the certificates presented.
address.certificatePinner!!.check(address.url.host(), address.certificatePinner!!.check(address.url.host,
unverifiedHandshake.peerCertificates) unverifiedHandshake.peerCertificates)
// Success! Save the handshake and the ALPN protocol. // Success! Save the handshake and the ALPN protocol.
@ -497,7 +497,7 @@ class RealConnection(
if (!this.route.address().equalsNonHost(address)) return false if (!this.route.address().equalsNonHost(address)) return false
// If the host exactly matches, we're done: this connection can carry the address. // If the host exactly matches, we're done: this connection can carry the address.
if (address.url.host() == this.route().address().url.host()) { if (address.url.host == this.route().address().url.host) {
return true // This connection is a perfect match. return true // This connection is a perfect match.
} }
@ -518,7 +518,7 @@ class RealConnection(
// 4. Certificate pinning must match the host. // 4. Certificate pinning must match the host.
try { try {
address.certificatePinner!!.check(address.url.host(), handshake()!!.peerCertificates) address.certificatePinner!!.check(address.url.host, handshake()!!.peerCertificates)
} catch (_: SSLPeerUnverifiedException) { } catch (_: SSLPeerUnverifiedException) {
return false return false
} }
@ -543,17 +543,17 @@ class RealConnection(
fun supportsUrl(url: HttpUrl): Boolean { fun supportsUrl(url: HttpUrl): Boolean {
val routeUrl = route.address().url val routeUrl = route.address().url
if (url.port() != routeUrl.port()) { if (url.port != routeUrl.port) {
return false // Port mismatch. return false // Port mismatch.
} }
if (url.host() == routeUrl.host()) { if (url.host == routeUrl.host) {
return true // Host match. The URL is supported. return true // Host match. The URL is supported.
} }
// We have a host mismatch. But if the certificate matches, we're still good. // We have a host mismatch. But if the certificate matches, we're still good.
return handshake != null && OkHostnameVerifier.verify( return handshake != null && OkHostnameVerifier.verify(
url.host(), handshake!!.peerCertificates[0] as X509Certificate) url.host, handshake!!.peerCertificates[0] as X509Certificate)
} }
@Throws(SocketException::class) @Throws(SocketException::class)
@ -690,7 +690,7 @@ class RealConnection(
override fun protocol(): Protocol = protocol!! override fun protocol(): Protocol = protocol!!
override fun toString(): String { override fun toString(): String {
return "Connection{${route.address().url.host()}:${route.address().url.port()}," + return "Connection{${route.address().url.host}:${route.address().url.port}," +
" proxy=${route.proxy()}" + " proxy=${route.proxy()}" +
" hostAddress=${route.socketAddress()}" + " hostAddress=${route.socketAddress()}" +
" cipherSuite=${handshake?.cipherSuite ?: "none"}" + " cipherSuite=${handshake?.cipherSuite ?: "none"}" +

View File

@ -240,7 +240,7 @@ class RealConnectionPool(
if (failedRoute.proxy().type() != Proxy.Type.DIRECT) { if (failedRoute.proxy().type() != Proxy.Type.DIRECT) {
val address = failedRoute.address() val address = failedRoute.address()
address.proxySelector.connectFailed( address.proxySelector.connectFailed(
address.url.uri(), failedRoute.proxy().address(), failure) address.url.toUri(), failedRoute.proxy().address(), failure)
} }
routeDatabase.failed(failedRoute) routeDatabase.failed(failedRoute)

View File

@ -99,7 +99,7 @@ class RouteSelector(
listOf(proxy) listOf(proxy)
} else { } else {
// Try each of the ProxySelector choices until one connection succeeds. // Try each of the ProxySelector choices until one connection succeeds.
val proxiesOrNull = address.proxySelector.select(url.uri()) val proxiesOrNull = address.proxySelector.select(url.toUri())
if (proxiesOrNull != null && proxiesOrNull.isNotEmpty()) { if (proxiesOrNull != null && proxiesOrNull.isNotEmpty()) {
proxiesOrNull.toImmutableList() proxiesOrNull.toImmutableList()
} else { } else {
@ -117,7 +117,7 @@ class RouteSelector(
private fun nextProxy(): Proxy { private fun nextProxy(): Proxy {
if (!hasNextProxy()) { if (!hasNextProxy()) {
throw SocketException( throw SocketException(
"No route to ${address.url.host()}; exhausted proxy configurations: $proxies") "No route to ${address.url.host}; exhausted proxy configurations: $proxies")
} }
val result = proxies[nextProxyIndex++] val result = proxies[nextProxyIndex++]
resetNextInetSocketAddress(result) resetNextInetSocketAddress(result)
@ -134,8 +134,8 @@ class RouteSelector(
val socketHost: String val socketHost: String
val socketPort: Int val socketPort: Int
if (proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.SOCKS) { if (proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.SOCKS) {
socketHost = address.url.host() socketHost = address.url.host
socketPort = address.url.port() socketPort = address.url.port
} else { } else {
val proxyAddress = proxy.address() val proxyAddress = proxy.address()
require(proxyAddress is InetSocketAddress) { require(proxyAddress is InetSocketAddress) {

View File

@ -144,7 +144,7 @@ class Transmitter(
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())
} }

View File

@ -55,8 +55,8 @@ object RequestLine {
* URL is. Includes the query component if it exists. * URL is. Includes the query component if it exists.
*/ */
fun requestPath(url: HttpUrl): String { fun requestPath(url: HttpUrl): String {
val path = url.encodedPath() val path = url.encodedPath
val query = url.encodedQuery() val query = url.encodedQuery
return if (query != null) "$path?$query" else path return if (query != null) "$path?$query" else path
} }
} }

View File

@ -278,7 +278,7 @@ class RetryAndFollowUpInterceptor(private val client: OkHttpClient) : Intercepto
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. // 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.

View File

@ -166,7 +166,7 @@ class Http2ExchangeCodec(
if (host != null) { if (host != null) {
result.add(Header(TARGET_AUTHORITY, host)) // Optional. result.add(Header(TARGET_AUTHORITY, host)) // Optional.
} }
result.add(Header(TARGET_SCHEME, request.url().scheme())) result.add(Header(TARGET_SCHEME, request.url().scheme))
for (i in 0 until headers.size) { for (i in 0 until headers.size) {
// header names must be lowercase. // header names must be lowercase.