Search code examples
javarestjerseyclient

How do I use an SSL client certificate with jersey client in java


I am trying to connect server using https url But still could not understand how should I add SSL certificate to jersey client

private static String post() throws Exception { String url ="https://www.test.lk/services/erl/es/erl/view/index.action";

    Client client =createClient();
    try {
        return client
                .target(url)
                .request()
                .get()
                .readEntity(String.class);
    } finally {
        client.close();
    }
}


private static Client createClient() throws Exception {
    SSLContext ctx = SSLContext.getInstance("SL");
    ctx.init(null, getTrustManager(), new SecureRandom());

    HostnameVerifier verifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostName, SSLSession sslSession) {
            return true;
        }
    };

    return ClientBuilder.newBuilder().sslContext(ctx).hostnameVerifier(verifier).build();
}

private static TrustManager[] getTrustManager() {
    return new TrustManager[] { new X509TrustManager() {
        
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Trust all servers
        }
        
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Trust all clients
        }
    } };
}

Solution

  • I found the solution. I just need to add certificate to the java KeyStore This helped me