Nuclos HTTPS: HttpsURLConnection, TrustManager, HostnameVerifier, SSLContext, no certificate, Java.

globe with meridians Language: Deutsch · English

open book Code example for general HTTPS access without a certificate

HttpsURLConnection without certificate validation – for testing only.

Disables certificate validation – for testing/development only, never in production.

General HTTPS access via HttpsURLConnection without certificate validation (NullTrustManager/NullHostnameVerifier):

public class SSLExample {

   public static void main(String[] args) throws IOException {
      String sUrl = "https://sshrest.de";

      trustAllCertificates();

      URL url = new URL(sUrl);
      URLConnection urlConnection = url.openConnection();
      InputStream is = urlConnection.getInputStream();

      is.read();
      is.close();
   }

   private static void trustAllCertificates() {
      try {
         TrustManager[] trustManagerArray = {new NullX509TrustManager()};
         SSLContext sc = SSLContext.getInstance("SSL");
         sc.init(null, trustManagerArray, null);
         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
         HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   /**
    * Host name verifier that does not perform any checks.
    */
   private static class NullHostnameVerifier implements HostnameVerifier {
      public boolean verify(String hostname, SSLSession session) {
         return true;
      }
   }

   /**
    * Trust manager that does not perform any checks.
    */
   private static class NullX509TrustManager implements X509TrustManager {
      public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
      }

      public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
      }

      public X509Certificate[] getAcceptedIssuers() {
         return new X509Certificate[0];
      }
   }

}

Related pages

gear Code example for SSL REST access without a certificate


SSL REST.

Öffnen →