Android中的Grpc捕获异常

时间:2020-08-25 11:37:12

标签: android http grpc

当在Android少用28api的情况下尝试使用grpc时,我收到类似“ io.grpc.StatusRuntimeException:UNAVAILABLE”的错误(在较高的工作效率下) 初始化类grpc客户端

private fun provideHttpClient(context: Context): OkHttpChannelBuilder {
    Security.insertProviderAt(Conscrypt.newProvider(), 1)
    val sslContext: SSLContext
    val trustManagers: Array<TrustManager>
    try {
        val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
        keyStore.load(null, null)
        val certInputStream = context.assets.open("ca.cert")
        val bis = BufferedInputStream(certInputStream)
        val certificateFactory = CertificateFactory.getInstance("X.509")
        while (bis.available() > 0) {
            val cert = certificateFactory.generateCertificate(bis)
            keyStore.setCertificateEntry(BASE_URL, cert)
        }
        val trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)
        trustManagers = trustManagerFactory.trustManagers
        sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, trustManagers, null)
        return OkHttpChannelBuilder.forAddress(BASE_URL, 50051)
            .sslSocketFactory(sslContext.socketFactory)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return OkHttpChannelBuilder.forAddress(BASE_URL, 50051)
}

在更少的android 28 API中我该怎么办?

0 个答案:

没有答案