1

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 ?

Rohit Jakhar
  • 1,231
  • 2
  • 12
  • 21

2 Answers2

2

Here is a solution working with Coil 1.0/2.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()
Hrk
  • 2,725
  • 5
  • 29
  • 44
-1

Add this line to your AndroidManifest.xml in the <application> tag:

android:usesCleartextTraffic="true"
Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • It works but you open the unsecure connection for the whole app, this is not recommended at all. – Hrk Mar 03 '22 at 16:50