Search code examples
javasslwebservice-client

how to build a web service client through ssl


I'm new to SSL and security and I want to build a java client for a web service that uses SSL. the server is properly configured to use two way ssl configuration, but how to build the client..

also if spring has anything for this it will be good..
thanks in advance


Solution

  • to get things work you have to create a client keystore and truststore, then define SSLContext with these stores, then instantiate SSLSocketFactory to produce SSLSockets like this:

    SSLContext sslcontext = SSLContexts.createDefault();        
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();    
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
    

    you should read this http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html to understand how it works.
    also this question how to write java client and server applications that uses mutual ssl authentication between them? may be useful.