You retrieve the sslService
from the service registry by using a plug-in.
Procedure
- Using a plug-in, invoke the
getService()
method from IServiceRegistry and retrieve an ISslService interface.Note:If the plug-in is Spring-based, you can define the service dependencies, or auto-wire, ISslService.
import ch.dunes.vso.sdk.IServiceRegistryAdaptor; import ch.dunes.vso.sdk.ssl.ISslService; public final class PluginAdaptor implements IServiceRegistryAdaptor { @Override public void setServiceRegistry(IServiceRegistry registry) { ISslService sslService = (ISslService) registry.getService(IServiceRegistry.SSL_SERVICE); } }
- After you retrieve the sslService, assign the service reference as a field.
In this way, the plug-in does not search in the registry, every time it uses the service. sslService provides two interfaces - SslContext and HostNameVerifier.
public interface ISslService { SSLContext newSslContext(String protocol) throws NoSuchAlgorithmException; HostnameVerifier newHostNameVerifier(); }
- Create a new SslContext object and specify the desired protocol.
SSLContext sslContext = sslService.getSslContext("TLS");
- Create an SSLSocketFactory class.
SSLSocketFactory factory = sslContext.getSocketFactory();
The factory class creates a socket with some specified options:
host
,port
,autoClose
,localAddress
,localPort
, andlocalhost
. - Set SSLSocketFactory to an HTTPS connection.
URL url = new URL(serverUrl); //a string with some serverUrl URLConnection connection = url.openConnection(); HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; SSLContext sslContext = sslService.newSslContext("TLS"); httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory()); httpsConnection.setHostnameVerifier(sslService.newHostNameVerifier());
- When a URLConnection is open, use the HostNameVerifier interface.
URL url = new URL(serverUrl); //a string with some serverUrl URLConnection connection = url.openConnection(); HostnameVerifier hostnameVerifier = sslService.newHostNameVerifier(); ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);