记一次Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure报错
项目中需要用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; }