https下的證書信任
阿新 • • 發佈:2019-02-03
package org.jiahao.weixin.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 自定義信任管理器類 * @author Alvin * 自定義信任管理器類的所有方法都是空的實現,表示信任任何伺服器端、客戶端的證書。 */ public class MyX509TrustManager implements X509TrustManager { // 檢查客戶端證書 @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } // 檢查伺服器端證書 @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } // 返回受信任的X509證書陣列 @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
一般這種方法是存在危險的,因為它能對任何https網站的證書信任,通常情況下,會在checkClientTrusted和checkServerTrusted兩個方法下進行邏輯驗證的處理。
/** * 處理https GET/POST請求 * * @param requestUrl * 請求的地址 * @param requestMethod * 請求的方法(GET/POST) * @param inputString * 請求體 * @return */ public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) { StringBuffer buffer = null; try { // 建立SSLContext SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); TrustManager[] tm = { new MyX509TrustManager() }; // 初始化 sslContext.init(null, tm, new java.security.SecureRandom()); // 獲取SSLSocketFacroty物件 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(requestMethod); // 設定當前例項使用的SSLSocketFactory物件 conn.setSSLSocketFactory(ssf); conn.connect(); // 往伺服器端寫內容 if (null != outputStr) { OutputStream os = conn.getOutputStream(); os.write(outputStr.getBytes("utf-8")); } // 讀取伺服器返回的內容 InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); buffer = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { buffer.append(line); } // System.out.println(buffer.toString()); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); }