Skip to content

Instantly share code, notes, and snippets.

@namhyun-gu
Last active November 7, 2022 15:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namhyun-gu/df668e651fe445a55c836284cfbdb215 to your computer and use it in GitHub Desktop.
Save namhyun-gu/df668e651fe445a55c836284cfbdb215 to your computer and use it in GitHub Desktop.
Basic Auth (Okhttp3)
// 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