There's a better alternative to trusting all certificates: Create a TrustStore
that specifically trusts a given certificate and use this to create a SSLContext
from which to get the SSLSocketFactory
to set on the HttpsURLConnection
. Here's the complete code:
File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
You can alternatively load the KeyStore
directly from a file or retrieve the X.509 Certificate from any trusted source.
Note that with this code, the certificates in cacerts
will not be used. This particular HttpsURLConnection
will only trust this specific certificate.