記一次Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure報錯
阿新 • • 發佈:2021-11-10
專案中需要用java呼叫第三方的https的介面,除錯了好多次總是報javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure錯誤,皇天不負苦心人最後終於除錯成功,廢話不多說直接上程式碼(我程式碼放的比較全,也方便以後自己檢視如何使用);
public static String signature(String comeStr) throws Exception { SSLContext sc = createIgnoreVerifySSL();//呼叫 String serverURL = "https://xxx"; StringBuffer sbf = new StringBuffer(); String strRead = null; URL url = new URL(serverURL); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(sc.getSocketFactory()); connection.setRequestMethod("POST");// 請求post方式 connection.setDoInput(true); connection.setDoOutput(true); // header內的的引數在這裡set connection.setRequestProperty("健, "值"); connection.setRequestProperty("Accept", "application/json");// 設定接收資料的格式 connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // body引數在這裡put到JSONObject中 JSONObject outParm = new JSONObject(jsonBuild());//需要轉換的json資料 writer.write(outParm.toString()); writer.flush(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((strRead = reader.readLine()) != null) { sbf.append(strRead); // sbf.append("\r\n"); } String jsonStr = sbf.toString().replace("\"", "'"); reader.close(); connection.disconnect(); JSONObject inParm = new JSONObject(jsonStr); String results = (String) inParm.get("pdf"); return results; }
/** * 獲取SSL套接字物件 重點重點:設定tls協議的版本 * @return */ public static SSLContext createIgnoreVerifySSL() { SSLContext sc = null; try {
//劃重點:這裡極其重要需要對應對方的TLS版本,版本也不多網上搜一搜,放進來一個個試(大部分用的TLSv1.2版本) sc = SSLContext.getInstance("TLSv1.2");// 指定TLS版本 } catch (NoSuchAlgorithmException e) { System.out.println("建立套接字失敗!"); e.printStackTrace(); } SSLSessionContext sslsc = sc.getServerSessionContext(); sslsc.setSessionTimeout(0); // 實現X509TrustManager介面,用於繞過驗證 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; try { sc.init(null, new TrustManager[] { trustManager }, null); } catch (KeyManagementException e) { System.out.println("初始化套接字失敗!"); e.printStackTrace(); } return sc; }