Last active
November 7, 2022 15:13
-
-
Save namhyun-gu/df668e651fe445a55c836284cfbdb215 to your computer and use it in GitHub Desktop.
Basic Auth (Okhttp3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See also: http://stackoverflow.com/questions/22490057/android-okhttp-with-basic-authentication | |
// Uses authenticator | |
fun login(val id: String, val password: String) { | |
var client = OkHttpClient() | |
client.authenticator = object:Authenticator() { | |
@Throws(IOException::class) | |
fun authenticate(route: Route, response: Response): Request { | |
var credential = Credentials.basic(id, password) | |
var request = response.request | |
.newBuilder() | |
.addHeader("Authorization", credential) | |
.build() | |
return request | |
} | |
} | |
} | |
} | |
// Uses Interceptor | |
class BasicInterceptor(id: String, password: String) : Interceptor { | |
lateinit var credentials: String | |
init { | |
credentials = Credentials.basic(id, password) | |
} | |
@Throws(IOException::class) | |
fun intercept(chain: Chain): Response { | |
var request = chain.request() | |
var builder = request.newBuilder().header("Authorization", credentials) | |
return chain.proceed(builder.build()) | |
} | |
} | |
var client = OkHttpClient.Builder() | |
.addInterceptor(BasicAuthInterceptor(id, password)) | |
.build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment