java - ignore expired ssl certificate

后端 未结 3 2236
自闭症患者
自闭症患者 2020-11-27 07:20
URL myUrl = new URL(\"https://www.....\");

SSL Certificate of website is expired. How to avoid it and make URL() work ?

3条回答
  •  暖寄归人
    2020-11-27 07:50

    You have to create a custom X509 validator that will ignore expired certificates. In fact, no check will be performed.

    Code taken from here: http://exampledepot.com/egs/javax.net.ssl/TrustAll.html

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };
    
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
    
    // Now you can access an https URL without having the certificate in the truststore
    // It should work with expired certificate as well
    try {
        URL myUrl = new URL("https://www.....");
    } catch (MalformedURLException e) {
    }
    

提交回复
热议问题