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

时间:2019-03-04 05:19:10

标签: android kotlin okhttp okhttp3 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时,为什么协议显示为http?有什么方法可以设置。请帮助我解决此问题。

2 个答案:

答案 0 :(得分:1)

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

替换

    val client = getUnsafeOkHttpClient()

使用

    val client = getUnsafeOkHttpClient().build()

答案 1 :(得分:1)

基本上,问题在于请求正文。将数据类与请求主体映射存在一些问题,这就是为什么它显示404错误。无论如何解决了