1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-10 11:03:02 +03:00

Convert JavaNetAuthenticator to Kotlin (#4909)

* Rename JavaNetAuthenticator.java to .kt

* Convert JavaNetAuthenticator to Kotlin
This commit is contained in:
Jesse Wilson
2019-04-09 22:56:52 -07:00
committed by GitHub
parent ff9c8ebcc6
commit ab85960cdb
3 changed files with 89 additions and 76 deletions

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.IOException
import java.net.Authenticator
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxy
/**
* Adapts [Authenticator] to [okhttp3.Authenticator]. Configure OkHttp to use [Authenticator] with
* [OkHttpClient.Builder.authenticator] or [OkHttpClient.Builder.proxyAuthenticator].
*/
class JavaNetAuthenticator : okhttp3.Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
val challenges = response.challenges()
val request = response.request()
val url = request.url()
val proxyAuthorization = response.code() == 407
val proxy = route?.proxy() ?: Proxy.NO_PROXY
for (challenge in challenges) {
if (!"Basic".equals(challenge.scheme(), ignoreCase = true)) {
continue
}
val auth = if (proxyAuthorization) {
val proxyAddress = proxy.address() as InetSocketAddress
Authenticator.requestPasswordAuthentication(
proxyAddress.hostName,
proxy.connectToInetAddress(url),
proxyAddress.port,
url.scheme(),
challenge.realm(),
challenge.scheme(),
url.url(),
Authenticator.RequestorType.PROXY
)
} else {
Authenticator.requestPasswordAuthentication(
url.host(),
proxy.connectToInetAddress(url),
url.port(),
url.scheme(),
challenge.realm(),
challenge.scheme(),
url.url(),
Authenticator.RequestorType.SERVER
)
}
if (auth != null) {
val credentialHeader = if (proxyAuthorization) "Proxy-Authorization" else "Authorization"
val credential = Credentials.basic(
auth.userName, String(auth.password), challenge.charset())
return request.newBuilder()
.header(credentialHeader, credential)
.build()
}
}
return null // No challenges were satisfied!
}
@Throws(IOException::class)
private fun Proxy.connectToInetAddress(url: HttpUrl): InetAddress {
return when {
type() == Proxy.Type.DIRECT -> InetAddress.getByName(url.host())
else -> (address() as InetSocketAddress).address
}
}
}