在Java的編程世界里面,我們有的時候,會經常訪問一些HTTPS的網站,那么訪問這些HTTPS的網站的時候,如果當前這個網站是自己企業內部的已知 的網站,或者我們信任的網站,這個時候,我們為了編寫程序的方便,就不需要把當前網站的服務器的根證書以及中間證書導入到JKS里面,讓在程序在調用HTTP協議的時候對服務器的服務器名和證書名進行對比。說了這么多,那么應該如何做呢?其實也挺簡單的,請看下面的Java代碼。
# 在類的開頭加入一段static的代碼
static { try { trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier ( new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { // TODO Auto-generated method stub return true; } } ); } catch (Exception e) {} }
# trustAllHttpsCertificates()方法的實現
private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException{ TrustManager[] trustAllCerts = new TrustManager[1]; trustAllCerts[0] = (TrustManager) new TrustAllManager(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory( sc.getSocketFactory()); } private static class TrustAllManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { } public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { } } }
簡單吧!!!!!
原文鏈接:https://blog.csdn.net/chancein007/article/details/74157144
