Error reporting javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException

Keywords: Java SSL IIS Mobile

Copyright Statement: This article is the original article of the blogger. It can not be reproduced without the permission of the blogger. https://blog.csdn.net/u010248330/article/details/70161899

  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9. import java.net.URLConnection;  
  10. import java.util.Iterator;  
  11.   
  12. import javax.imageio.ImageIO;  
  13. import javax.imageio.ImageReader;  
  14. import javax.imageio.stream.ImageInputStream;  
  15.   
  16.   
  17. public class TestDownLoadImage {  
  18.       
  19.     public static void main(String[] args) {  
  20.          String url="http://wx1.sinaimg.cn/mw690/006sl6kBgy1fel3aq0nyej30i20hxq7i.jpg";  
  21.          String downToFilePath="d:/download/image/";  
  22.          String fileName="test";  
  23.          imageDownLoad(url, downToFilePath,fileName);  
  24.           
  25.     }  
  26.     public static void  imageDownLoad(String urlString, String filepath,String filename) {  
  27.           
  28.         InputStream is =null;  
  29.         ImageInputStream iis=null;  
  30.         OutputStream os =null;  
  31.         String downloadPath=null;  
  32.         try {  
  33.               
  34.             URL url = new URL(urlString);  
  35.             URLConnection con = url.openConnection();  
  36.             is = con.getInputStream();  
  37.             iis=ImageIO.createImageInputStream(is);  
  38.             Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);    
  39.             if (!iter.hasNext()) {    
  40.                 return  ;    
  41.             }    
  42.             ImageReader reader = iter.next();    
  43.              //Read file format jpg, etc.  
  44.             String imgFormat=reader.getFormatName();    
  45.             byte[] bs = new byte[1024];  
  46.             int len;  
  47.             File file=new File(filepath);  
  48.             if(!file.exists()){           
  49.                 file.mkdir();  
  50.             }  
  51.             downloadPath=filepath+"//"+filename+"."+imgFormat;  
  52.             os = new FileOutputStream(downloadPath);  
  53.             while ((len = iis.read(bs)) != -1) {  
  54.               os.write(bs, 0, len);  
  55.             }  
  56.         } catch (MalformedURLException e) {  
  57.             e.printStackTrace();  
  58.         } catch (FileNotFoundException e) {  
  59.             e.printStackTrace();  
  60.         } catch (IOException e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.         finally{  
  64.             try {  
  65.                 os.close();  
  66.                 is.close();  
  67.                 iis.close();  
  68.             } catch (IOException e) {  
  69.                 e.printStackTrace();  
  70.             }   
  71.         }  
  72.         return ;  
  73.     }     
  74.   
  75. }  

This code can download pictures normally. No problem.


Later, I came across an image whose address was https, String url="https://05.imgmini.eastday.com/mobile/20170413/20170413053046_4a5e70ed0b39c824517630e6954861f2_1.jpeg";

The code is wrong.

Report errors:

  1. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  2.     at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)  
  3.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)  
  4.     at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)  
  5.     at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)  
  6.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1209)  
  7.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:135)  
  8.     at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)  
  9.     at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)  
  10.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)  
  11.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)  
  12.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)  
  13.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)  
  14.     at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)  
  15.     at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)  
  16.     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)  
  17.     at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)  
  18.     at TestDownLoadImage.imageDownLoad(TestDownLoadImage.java:43)  
  19.     at TestDownLoadImage.main(TestDownLoadImage.java:30)  
  20. Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  21.     at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)  
  22.     at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)  
  23.     at sun.security.validator.Validator.validate(Validator.java:218)  
  24.     at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)  
  25.     at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)  
  26.     at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)  
  27.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1188)  
  28.     ... 13 more  
  29. Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  30.     at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)  
  31.     at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)  
  32.     at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)  
  33.     ... 19 more  
  34. Exception in thread "main" java.lang.NullPointerException  
  35.     at TestDownLoadImage.imageDownLoad(TestDownLoadImage.java:72)  
  36.     at TestDownLoadImage.main(TestDownLoadImage.java:30)  

Looking up the information on the Internet is a certificate problem, you can write a logic in the code to ignore the certificate:

Here is the code downloaded online: http://www.sojson.com/blog/195.html


  1. import java.security.cert.CertificateException;  
  2. import java.security.cert.X509Certificate;  
  3.    
  4. import javax.net.ssl.HostnameVerifier;  
  5. import javax.net.ssl.HttpsURLConnection;  
  6. import javax.net.ssl.SSLContext;  
  7. import javax.net.ssl.SSLSession;  
  8. import javax.net.ssl.TrustManager;  
  9. import javax.net.ssl.X509TrustManager;  
  10.    
  11. public class SslUtils {  
  12.    
  13.     public static void trustAllHttpsCertificates() throws Exception {  
  14.         TrustManager[] trustAllCerts = new TrustManager[1];  
  15.         TrustManager tm = new miTM();  
  16.         trustAllCerts[0] = tm;  
  17.         SSLContext sc = SSLContext.getInstance("SSL");  
  18.         sc.init(null, trustAllCerts, null);  
  19.         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
  20.     }  
  21.    
  22.     static class miTM implements TrustManager,X509TrustManager {  
  23.         public X509Certificate[] getAcceptedIssuers() {  
  24.             return null;  
  25.         }  
  26.    
  27.         public boolean isServerTrusted(X509Certificate[] certs) {  
  28.             return true;  
  29.         }  
  30.    
  31.         public boolean isClientTrusted(X509Certificate[] certs) {  
  32.             return true;  
  33.         }  
  34.    
  35.         public void checkServerTrusted(X509Certificate[] certs, String authType)  
  36.                 throws CertificateException {  
  37.             return;  
  38.         }  
  39.    
  40.         public void checkClientTrusted(X509Certificate[] certs, String authType)  
  41.                 throws CertificateException {  
  42.             return;  
  43.         }  
  44.     }  
  45.        
  46.     /** 
  47.      * The SSL certificate that ignores the HTTPS request must be invoked before openConnection 
  48.      * @throws Exception 
  49.      */  
  50.     public static void ignoreSsl() throws Exception{  
  51.         HostnameVerifier hv = new HostnameVerifier() {  
  52.             public boolean verify(String urlHostName, SSLSession session) {  
  53.                 return true;  
  54.             }  
  55.         };  
  56.         trustAllHttpsCertificates();  
  57.         HttpsURLConnection.setDefaultHostnameVerifier(hv);  
  58.     }  
  59. }  
//Use it before URLConnection con = url.openConnection()
  1.     
  2.   
  3. public static void main(String[] args) {  
  4.      //String url="http://wx1.sinaimg.cn/mw690/006sl6kBgy1fel3aq0nyej30i20hxq7i.jpg";  
  5.      String url="https://05.imgmini.eastday.com/mobile/20170413/20170413053046_4a5e70ed0b39c824517630e6954861f2_1.jpeg";  
  6.      String downToFilePath="d:/download/image/";  
  7.      String fileName="test";  
  8.      try {  
  9.         SslUtils.ignoreSsl();  
  10.     } catch (Exception e) {  
  11.         e.printStackTrace();  
  12.     }  
  13.      imageDownLoad(url, downToFilePath,fileName);  
  14.       
  15. }  

Posted by antonello on Tue, 05 Feb 2019 21:51:18 -0800