Allow insecure SSL in Java 11 HttpClient

Carvia Tech | November 24, 2019 | 1 min read | 1,272 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. Diamond Problem of Inheritance in Java 8
  3. Is Java Pure Object Oriented Language?
  4. Difference between Comparable and Comparator in Java
  5. can we write a java method that swaps two integers
  6. What is ThreadLocal in Java, where will you use this class
  7. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock

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