本身这个问题之前未找到很好的解决办法,本地请求Https请求URL时,一直没有问题,在线上服务器上时,总是出现javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure的问题,
1、开始以为双方的协议不一致,修改了协议范围后,仍然不行
//可以打印请求过程,查询对方协议 System.setProperty("javax.net.debug", "all"); //然后可以请求前设置 System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,TLSv1.0,SSLv3");
2、后来继续查询,从java8 Update31开始,由于SSL协议中的安全漏洞,默认情况下禁用SSL v3协议,需要找到jvm下的java.security文件,路径示例:jdk/Contents/Home/jre/lib/security,
定位参数所在行数 cat -n java.security |grep 'jdk.tls.disabledAlgorithms' 直接按行数编辑(示例100行) #vi +100 java.security jdk.tls.disabledAlgorithms= SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \ DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \ include jdk.disabled.namedCurves 删除 SSLv3, TLSv1,TLSv1.1
以上方法使用后问题依旧存在,于是就想着跳过这个协议验证
3、于是开启了第三种方法,来个釜底抽薪,
HttpsURLConnection connection = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 connection = (HttpsURLConnection) realUrl.openConnection(); // 创建信任所有服务器的TrustManager TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // 初始化SSLContext并设置TrustManager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); // 从SSLContext获取SSLSocketFactory并设置到HttpsURLConnection中 connection.setSSLSocketFactory(sc.getSocketFactory()); // 设置通用的请求属性 connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("contentType", "utf-8"); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"); // 建立实际的连接 connection.connect(); in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = in.readLine()) != null) { line = new String(line.getBytes()); result.append(line); } } catch (Exception e) { e.printStackTrace(); }
当然这种方法不建议使用,不安全,如有更好的方法,可以下面评论,共同学习共同进步
还没有评论,来说两句吧...