Search code examples
android-studiokotlincoil

How to load image in Coil with https not secure certificate


I am trying to load an image from not-secure link (not have SSL certificate) using Coil Library in Kotlin and it failed to load it and load error image. Is there any way to load image from not-secure link ?


Solution

  • Here is a solution working with Coil 1.0/2.0/3.0.

    It's not a perfect solution because the okhttp cache is not shared with the default ImageLoader, but in my case it could help for a specific part of the application where I have unknown image url coming from 3rd party provider (Amazon Prime and so on). I use it in Android TV launcher with image urls coming for recommandation channel.

        @SuppressLint("CustomX509TrustManager")
        private fun initUntrustImageLoader(): ImageLoader {
            // Create a trust manager that does not validate certificate chains
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                @SuppressLint("TrustAllX509TrustManager")
                override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
    
                @SuppressLint("TrustAllX509TrustManager")
                override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
    
                override fun getAcceptedIssuers(): Array<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 client = OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
                    .hostnameVerifier { _, _ -> true }.build()
    
    
            return ImageLoader.Builder(context)
                .okHttpClient(client)
                .build()
        }
    

    At the beginning of my class, I instanciate it with

    private var untrustImageLoader: ImageLoader = initUntrustImageLoader()