Skip to content

Instantly share code, notes, and snippets.

@seccomiro
Last active July 9, 2024 08:15
Show Gist options
  • Save seccomiro/85446c4849855615d1938133bce30738 to your computer and use it in GitHub Desktop.
Save seccomiro/85446c4849855615d1938133bce30738 to your computer and use it in GitHub Desktop.
An adaptation in Kotlin of Rajasekhar's answer at https://stackoverflow.com/a/43366296/1148768
import okhttp3.Interceptor
import okhttp3.Credentials
import okhttp3.Response
import java.io.IOException
class BasicAuthInterceptor(user: String, password: String) : Interceptor {
private val credentials: String = Credentials.basic(user, password)
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build()
return chain.proceed(authenticatedRequest)
}
}
@Rusland3000
Copy link

Rusland3000 commented Jun 7, 2018

Hello.
I need POST query to "https://myserver.com" with Basic Authentification ("user", "pass").
How to use this class? Can you help?

@micer
Copy link

micer commented Nov 6, 2018

@Rusland3000 You need to add interceptor when building your OkHttp client:

OkHttpClient.Builder()
.addInterceptor(
    BasicAuthInterceptor(
        "user",
        "password"
    )
)

Copy link

ghost commented May 28, 2020

how we pass consumer key and Secret in post retrofit request which we do same as on postman by adding Authorization with type 0Auth 1.0 and there we add our consumer key and secret key , then hit the Api , our Api get success .....THis same can how be achieve in android kotlin or with Androi java, please help me...

Thanks in advance

@vtabk2
Copy link

vtabk2 commented Jul 9, 2024

Fatal Exception: java.net.SocketTimeoutException
timeout

BasicAuthInterceptor has more crash time out.
Help me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment