Java: “HTTPS hostname wrong” issue
Quick resolution to the error while connecting to any HTTPS API.
You have an HTTPS API connection which was working before or has stopped working (all of sudden) or getting the error (HTTPS hostname wrong), then this article will help you quickly understand.
Java error stack trace
Caused by: java.io.IOException: HTTPS hostname wrong: should be <api.feitest.com>
at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(HttpsClient.java:649)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:573)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
Reason
In most cases this is to do with misconfigured API servers certificate, non-CA issued cert.
When to apply:
The third party API may not accept / not possible to fix the certificate related issue and you need to make it WORKING.
Solution
Step 1: Bypass http client hostname check
Write the Java code to bypass certificate check / Custom Hostname Verifier. Reference: https://howtodoinjava.com/java/java-security/bypass-ssl-certificate-checking-java/. Many more articles available online.
Step 2: The Important Step
You need to set the property java.protocol.handler.pkgs=sun.net.www.protocol to your application launch.
Summary of Root Cause Analysis
Your certificate check / bypass code was attached to Java’s HttpsURLConnectionImpl (internally with the http libraries that you called) but if any of the request fails, it then starts using HttpsURLConnectionOldImpl which does not have your certificate check / bypass code. By writing step 2 you are telling java even the fallback should also go to HttpsURLConnectionImpl.
If you are curious to know the entire debugging and RCA, here is a beautiful article which will help you get to the bottom. https://www.polyglotdeveloper.com/cookbook/2016-12-24-HTTPS-hostname-wrong-sni-jre8/
Very high chances that you will face this issue with Weblogic, Websphere, JBoss and Glassfish due to the fact that it ships with its custom / versioned libraries which ignores the base Java installed libraries on web application launch.
Hope this helps.