androidkotlinsslokhttpself-signed-certificate

OKhttp Self sign certificate in Kotlin Android


I'm working for an Android Kotlin project with self-signed SSL cert.

I use Okhttp for connection with server but my app crashes when try to access the server IP and error is saying I need to self sign certificate to access.

I already did many tests by searching internet resources but non of them works for my code. Check my following code and suggest me for better fix.

Please note the URL I put here just for Sample.

val client = OkHttpClient()
var url = "https://00.00.00.000"

            val requestBody = FormBody.Builder()
                    .add("phone", "+9500000000")
                    .add("token", "03AGdBq26rMv")
                    .build()

            val request = Request.Builder().url(url)
                    .header("User-Agent", "OkHttp Headers.java")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .post(requestBody)
                    .build()
            val response = client.newCall(request).execute()
            return response.body?.string().toString()
            println("Response" + response.body?.string().toString())

Solution

  • The following code works for me when I put these few lines of code before building my Client connection.

    //set self sign certificate
    val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun checkClientTrusted(
            chain: Array<out X509Certificate>?, 
            authType: String?
        ) {}
    
        override fun checkServerTrusted(
            chain: Array<out X509Certificate>?, 
            authType: String?
        ) {}
    
        override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
    })
    
    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
    
    // connect to server
    val client = OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        .hostnameVerifier{ _, _ -> true }
        .build()