Allow insecure SSL in Java 11 HttpClient

Upasana | November 24, 2019 | 1 min read | 2,671 views

We will learn how to allow insecure SSL connections (expired certificate, self-signed certificates) in Java 11 HttpClient.

There could be various reasons for bad SSL - expired SSL certificate, wrong host in SSL certificate, self-signed certificate, untrusted root certificate, revoked certificate, weak key used for certificate, etc.

Using SSL Context settings

We will create and initialize an instance of SSLContext that accepts all SSL certificates without any kind of verification. Such SSL context shall never be used in production environment.

Java 11 HttpClient with Insecure SSLContext
fun testIgnoreSSL(url: String) {
    val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate>? = null
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) {}
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) {}

    val sslContext: SSLContext = SSLContext.getInstance("TLS")
    sslContext.init(null, trustAllCerts, SecureRandom())

    val httpClient = HttpClient.newBuilder()
            .sslContext(sslContext) // SSL context 'sc' initialised as earlier

    val requestBuilder = HttpRequest.newBuilder()

    val response = httpClient.send(requestBuilder, HttpResponse.BodyHandlers.ofString()); // sends the request

Disabling the host verification

If we just want to disable a particular check for hostname verification, then we can use either of the two below mentioned approaches:

Using command line argument to JVM
Programmatically setting the property before httpclient instance creation
val props = System.getProperties()
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true")
//TODO: Initialize the HttpClient now

That’s all.

Top articles in this category:
  1. Submit Form with Java 11 HttpClient - Kotlin
  2. Secure OTP generation in Java
  3. Is Java Pure Object Oriented Language?
  4. Discuss internals of a ConcurrentHashmap (CHM) in Java
  5. ConcurrentModificationException in Java
  6. HmacSHA256 Signature in Java
  7. Can two threads call two different synchronized instance methods of an Object?

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.