当前位置:   article > 正文

【解决】Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed

【解决】Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed

问题原因:

Java8及高版本以上的版本在源应用程序不信任目标应用程序的证书,因为在源应用程序的JVM信任库中找不到该证书或证书链。也就是目标站点启用了HTTPS 而缺少安全证书时出现的异常

解决方案:

我使用的是忽略证书验证

  1. public class Base64Util {
  2. public static String getBase64FromUrl(String fileUrl) {
  3. InputStream inputStream = null;
  4. byte[] data = null;
  5. ByteArrayOutputStream swapStream = null;
  6. HttpsURLConnection conn = null;
  7. try {
  8. URL url = new URL(fileUrl);
  9. //判断当前文件url是否是https
  10. if (fileUrl.contains("https:")){
  11. //是https
  12. //绕过证书
  13. SSLContext context = createIgnoreVerifySSL();
  14. conn = (HttpsURLConnection) url.openConnection();
  15. conn.setSSLSocketFactory(context.getSocketFactory());
  16. inputStream = conn.getInputStream();
  17. }else {
  18. //当前链接是http
  19. inputStream = url.openConnection().getInputStream();
  20. }
  21. swapStream = new ByteArrayOutputStream();
  22. byte[] buff = new byte[100];
  23. int rc = 0;
  24. while ((rc = inputStream.read(buff, 0, 100)) > 0) {
  25. swapStream.write(buff, 0, rc);
  26. }
  27. data = swapStream.toByteArray();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. } finally {
  31. IOUtils.closeQuietly(inputStream);
  32. IOUtils.closeQuietly(swapStream);
  33. }
  34. return new String(Base64.encodeBase64(data));
  35. }
  36. //绕过SSL、TLS证书
  37. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  38. SSLContext sc = SSLContext.getInstance("TLS");
  39. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  40. X509TrustManager trustManager = new X509TrustManager() {
  41. @Override
  42. public void checkClientTrusted(
  43. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  44. String paramString) throws CertificateException {
  45. }
  46. @Override
  47. public void checkServerTrusted(
  48. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  49. String paramString) throws CertificateException {
  50. }
  51. @Override
  52. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  53. return null;
  54. }
  55. };
  56. sc.init(null, new TrustManager[]{trustManager}, null);
  57. return sc;
  58. }
  59. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/489868
推荐阅读
相关标签
  

闽ICP备14008679号