Search code examples
javaspringrestsslclient

Not able to create client in Java while using apache HTTPS libraries


I am working on an application where I have to send the request to another server running. Whenever I try to create the client so that I can send my API request to server, it stuck there. It doesn't throw exception also and doesn't get executed. That thread just dies without doing anything. I debugged a lot by putting loggers after each line and found out SSL build line is having issues. If I try to execute same code from local machine, it gets executed cleanly but from my application, it fails. Can someone please let me know what is the exact issue.Here is the code which I have written for creating the client.I think the issue is related to certificates but in verify methods, it is saying setting everything as true.

private  HttpClient createClient() throws Exception {
        X509TrustManager x509TrustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {

            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {

            }
        };
        TrustManager[] trustManagers = new TrustManager[] {x509TrustManager};
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustManagers, new SecureRandom());
             // code works fine till here and after that this thread just dies.
        return HttpClients.custom().setSSLHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).setSSLContext(sslContext).build();
    }

Solution

  • The issue was with the version of httpcore version. Since I was using httpclient version greater than 4.5 and I have httpcore version lesser than 4. There were no issues with the code. If someone is creating a client using apache libraries, please make sure you are using versions updated.