android - 在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错

标签 android kotlin okhttp kotlin-android-extensions

我发现了很多与此相关的问题,并且我尝试了很多选择。但我无法解决它。我想禁用使用 okhttp 进行 API 调用时的认证检查。

下面是我尝试过的代码

import okhttp3.OkHttpClient
import java.security.cert.CertificateException
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

    class UnsafeOkHttpClient {
    companion object {
        fun getUnsafeOkHttpClient(): OkHttpClient.Builder {
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                    @Throws(CertificateException::class)
                    override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                    }

                    @Throws(CertificateException::class)
                    override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                    }

                    override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                        return arrayOf()
                    }
                })

                // Install the all-trusting trust manager
                val sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, java.security.SecureRandom())
                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory

                val builder = OkHttpClient.Builder()
                builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
                builder.hostnameVerifier { _, _ -> true }

                return builder
            } catch (e: Exception) {
                throw RuntimeException(e)
            }
        }
    }
}

提出请求时:

 fun getAppList(requestbody: AppListRequestBody, baseUrl: String): AppListResponse {

        val gson = GsonBuilder().create()
        val appListRequestInfo: String = gson.toJson(requestbody)
        val JSON = MediaType.parse("application/json")
        val appListBody: RequestBody = RequestBody.create(JSON, appListRequestInfo)
        val client =getUnsafeOkHttpClient().build

        var appListRequest: Request = Request.Builder()
                .url("$baseUrl/apps/mobile")
                .post(appListBody)
                .addHeader("Content-Type", "application/json")
                .build()
        val appResponse: Response = client.newCall(appListRequest).execute() //Getting syntax error
        if (!appResponse.isSuccessful) {
            Log.e("Exception =",appResponse.message())
            throw Exception(appResponse.code().toString())
        }
        Log.d("App list res",appResponse.body().toString())
        return Gson().fromJson(appResponse.body()!!.string(), AppListResponse::class.java)
    }

我遇到异常:

Response{protocol=http/1.1, code=404, message=Not Found}

请帮我解决这个问题。另外,为什么当 url 是 https 时它显示协议(protocol)为 http?有什么方法可以设置吗。请帮我解决这个问题。

最佳答案

您的getUnsafeOkHttpClient()返回一个OkHttpClient.Builder

替换

    val client = getUnsafeOkHttpClient()

    val client = getUnsafeOkHttpClient().build()

关于android - 在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977069/

相关文章:

java - 如何知道 HttpURLConnection 是否确实在底层套接字上发送了请求?

android - 用于在 ListView 中显示 SQLite 记录的 SimpleCursorAdaptor 替代方案

kotlin - 在 Swift 中使用协程流

php - OkHttp POST 似乎没有发送请求正文

Android okhttp 获取缓存响应

android - 多部分请求spring不绑定(bind)文件数据

Android 构建和安装错误 : INSTALL_PARSE_FAILED_NOT_APK

kotlin - 从 InputStream 读取的挂起函数

oop - 在源或包的顶层声明对象表达式的范围是什么?

android - 需要更新最低 SDK 版本 - 如何通过 Play 开发人员统计信息正确区分活跃用户和非活跃用户?