Java 17 - How to Properly Handle SSLHandshakeException When Using Apache HttpClient?
I'm stuck trying to I'm migrating some code and I'm trying to debug After trying multiple solutions online, I still can't figure this out. I've been struggling with this for a few days now and could really use some help. I'm currently working with an `SSLHandshakeException` when trying to make an HTTPS request using Apache HttpClient version 4.5.13 in a Java 17 application. The exception message indicates that the server's certificate chain could not be verified. This is quite frustrating since I've already imported the server's certificate into my Java keystore using the following command: ```bash keytool -import -alias myserver -file server-cert.pem -keystore cacerts ``` I've verified that the certificate is indeed in the keystore by running: ```bash keytool -list -keystore cacerts ``` However, I'm still getting the same `SSLHandshakeException`. Hereβs the relevant part of my code: ```java CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(SSLContexts.custom().loadTrustMaterial(new File("path/to/keystore.jks"), "password".toCharArray()).build()) .build(); HttpGet request = new HttpGet("https://myserver.com/api/data"); try (CloseableHttpResponse response = httpClient.execute(request)) { System.out.println(EntityUtils.toString(response.getEntity())); } catch (IOException e) { e.printStackTrace(); } ``` I've double-checked that the keystore path is correct and that the server's certificate is valid. Additionally, I've made sure that my application is set to use the correct keystore by adding the JVM argument: ```bash -Djavax.net.ssl.trustStore=path/to/keystore.jks ``` Despite these efforts, I'm still working with this behavior: ``` javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target ``` Is there something I'm missing here? Could there be an scenario with the intermediate certificates, or do I need to configure something else in my Apache HttpClient setup? Any guidance would be appreciated! For context: I'm using Java on Linux. What am I doing wrong? This is part of a larger service I'm building. What's the best practice here? The project is a application built with Java. I'd be grateful for any help. My development environment is Ubuntu 20.04. I'm on macOS using the latest version of Java. Thanks for taking the time to read this!