See Also: HttpsURLConnection Members
An Java.Net.HttpURLConnection for HTTPS (). A connected HttpsURLConnection allows access to the negotiated cipher suite, the server certificate chain, and the client certificate chain if any.
For example, to trust a set of certificates specified by a KeyStore:
java Example
KeyStore keyStore = ...; String algorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://www.example.com/"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream in = urlConnection.getInputStream();
It is possible to implement X509TrustManager directly instead of using one created by a TrustManagerFactory. While this is straightforward in the insecure case of allowing all certificate chains to pass verification, writing a proper implementation will usually want to take advantage of Java.Security.Cert.CertPathValidator. In general, it might be better to write a custom KeyStore implementation to pass to the TrustManagerFactory than to try and write a custom X509TrustManager.
For example, to supply client certificates from a KeyStore:
java Example
KeyStore keyStore = ...; String algorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), null, null); URL url = new URL("https://www.example.com/"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream in = urlConnection.getInputStream();
A X509KeyManager can also be implemented directly. This can allow an application to return a certificate and private key from a non-KeyStore source or to specify its own logic for selecting a specific credential to use when many may be present in a single KeyStore.