有时可能通过URLConnection写了个爬虫收集网站信息,请求https的url时,可能预到javax.net.ssl.SSLException: Not trusted server certificate 、java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found或javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name这几种异常。本文主要介绍针对这几种异常解决方法。

解决办法

上面的几种异常是请求不信任的https网站或配置有问题的https网站代码所抛出的异常。处理这几种异常,在代码添加一个静态的static代码块,做一下相关的配置,代码如下:

static {
    TrustManager[] trustAllCertificates = new TrustManager[] {
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null; // Not relevant.
            }
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
        }
    };
    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    };
    try {
        System.setProperty("jsse.enableSNIExtension", "false");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
    }
    catch (GeneralSecurityException e) {
        throw new ExceptionInInitializerError(e);
    }
}