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())
}
Allow insecure SSL in Java 11 HttpClient
Carvia Tech | 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
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:
- Submit Form with Java 11 HttpClient - Kotlin
- Secure OTP generation in Java
- Is Java Pure Object Oriented Language?
- Discuss internals of a ConcurrentHashmap (CHM) in Java
- ConcurrentModificationException in Java
- HmacSHA256 Signature in Java
- Can two threads call two different synchronized instance methods of an Object?
Find more on this topic:
Subscribe to Interview Questions
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..
Similar Posts
- Code review checklist for Java developers
- Count word frequency in Java
- Secure OTP generation in Java
- HmacSHA256 Signature in Java
- Submit Form with Java 11 HttpClient - Kotlin
- Java Exception Class Hierarchy
- Http download using Java NIO FileChannel
- CRC32 checksum calculation Java NIO
- Precision and scale for a Double in java
- Difference between HashMap, LinkedHashMap and TreeMap