Skip to content

Instantly share code, notes, and snippets.

@alexbezhan
Created June 19, 2018 08:21
Show Gist options
  • Save alexbezhan/7c4ec2cc365eba9ab201b4ff9b4f3aeb to your computer and use it in GitHub Desktop.
Save alexbezhan/7c4ec2cc365eba9ab201b4ff9b4f3aeb to your computer and use it in GitHub Desktop.
How to call Https with Retrofit 2 and OkHttpClient
object Retrofit2Https {
fun createHttpClient(context: Context): OkHttpClient {
// Loads "my_certificate.crt" from res/raw/my_certificate.crt
val cf: CertificateFactory = CertificateFactory.getInstance("X.509")
val caInput: InputStream = BufferedInputStream(context.resources.openRawResource(R.raw.my_certificate))
val ca: X509Certificate = caInput.use {
cf.generateCertificate(it) as X509Certificate
}
// Create a KeyStore with the certificate
val keyStoreType = KeyStore.getDefaultType()
val keyStore = KeyStore.getInstance(keyStoreType).apply {
load(null, null)
setCertificateEntry("ca", ca)
}
// Create a TrustManager that trusts the certificate
val tmfAlgorithm: String = TrustManagerFactory.getDefaultAlgorithm()
val tmf: TrustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm).apply {
init(keyStore)
}
// Create an SSLContext that uses our TrustManager
val context = SSLContext.getInstance("TLS").apply {
init(null, tmf.trustManagers, null)
}
val x509TrustManager = tmf.trustManagers.first() as X509TrustManager
return OkHttpClient()
.newBuilder()
.sslSocketFactory(context.socketFactory, x509TrustManager)
.build()
}
val retrofit = Retrofit.Builder()
.baseUrl("https://google.com")
.client(createHttpClient(context))
.build()
val myService = retrofit.create(MyService::class.java)
val response = myService.load().execute()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment