How To Add Trusted Certificate To Okhttp
I need to trust certificate of one specific site using OkHttp client. I have found a solution here: https://jebware.com/blog/?p=340 This code works well with the server I wanted to
Solution 1:
The first option is to add to the local keystore file, stored in the JRE directory.
But I've also used a custom trust manager that merges certificates https://github.com/yschimke/okurl/blob/07e79795e14b9163bcf4342f39c23020f51ecf64/src/main/kotlin/com/baulsupp/okurl/security/MergedX509TrustManager.kt
package com.baulsupp.okurl.security
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
classMergedX509TrustManager(privateval managers: List<X509TrustManager>) : X509TrustManager {
overridefuncheckClientTrusted(chain: Array<X509Certificate>, authType: String) {
throw UnsupportedOperationException()
}
overridefuncheckServerTrusted(chain: Array<X509Certificate>, authType: String) {
val exceptions = mutableListOf<CertificateException>()
for (tm in managers) {
try {
tm.checkServerTrusted(chain, authType)
return
} catch (e: CertificateException) {
exceptions.add(e)
}
}
throw bestException(exceptions)
}
funbestException(exceptions: List<CertificateException>): CertificateException {
if (exceptions.isNotEmpty()) {
// last is probably system keystorethrow exceptions[exceptions.size - 1]
} else {
throw CertificateException("no X509TrustManager to check")
}
}
overridefungetAcceptedIssuers(): Array<X509Certificate> {
val certificates = mutableListOf<X509Certificate>()
for (tm in managers) {
certificates.addAll(tm.acceptedIssuers.toList())
}
return certificates.toTypedArray()
}
}
Post a Comment for "How To Add Trusted Certificate To Okhttp"