Allow insecure SSL in Java 11 HttpClient

Carvia Tech | November 24, 2019 | 1 min read | 41 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()
            .connectTimeout(Duration.ofMillis(10000))
            .sslContext(sslContext) // SSL context 'sc' initialised as earlier
            .build()

    val requestBuilder = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .GET()
            .build()

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

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
-Djdk.internal.httpclient.disableHostnameVerification
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. Diamond Problem of Inheritance in Java 8
  2. Is Java Pure Object Oriented Language?
  3. can we write a java method that swaps two integers
  4. Difference between Comparable and Comparator in Java
  5. What is ThreadLocal in Java, where will you use this class
  6. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  7. What do you understand by Java Memory Model?


Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info