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
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.Iterator;
- import javax.imageio.ImageIO;
- import javax.imageio.ImageReader;
- import javax.imageio.stream.ImageInputStream;
- public class TestDownLoadImage {
- public static void main(String[] args) {
- String url="http://wx1.sinaimg.cn/mw690/006sl6kBgy1fel3aq0nyej30i20hxq7i.jpg";
- String downToFilePath="d:/download/image/";
- String fileName="test";
- imageDownLoad(url, downToFilePath,fileName);
- }
- public static void imageDownLoad(String urlString, String filepath,String filename) {
- InputStream is =null;
- ImageInputStream iis=null;
- OutputStream os =null;
- String downloadPath=null;
- try {
- URL url = new URL(urlString);
- URLConnection con = url.openConnection();
- is = con.getInputStream();
- iis=ImageIO.createImageInputStream(is);
- Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
- if (!iter.hasNext()) {
- return ;
- }
- ImageReader reader = iter.next();
- //Read file format jpg, etc.
- String imgFormat=reader.getFormatName();
- byte[] bs = new byte[1024];
- int len;
- File file=new File(filepath);
- if(!file.exists()){
- file.mkdir();
- }
- downloadPath=filepath+"//"+filename+"."+imgFormat;
- os = new FileOutputStream(downloadPath);
- while ((len = iis.read(bs)) != -1) {
- os.write(bs, 0, len);
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- finally{
- try {
- os.close();
- is.close();
- iis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return ;
- }
- }
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:
- 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
- at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
- at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
- at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
- at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
- at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1209)
- at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:135)
- at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
- at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
- at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
- at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
- at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
- at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
- at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
- at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
- at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
- at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
- at TestDownLoadImage.imageDownLoad(TestDownLoadImage.java:43)
- at TestDownLoadImage.main(TestDownLoadImage.java:30)
- Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
- at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
- at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
- at sun.security.validator.Validator.validate(Validator.java:218)
- at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
- at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
- at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
- at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1188)
- ... 13 more
- Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
- at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
- at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
- at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
- ... 19 more
- Exception in thread "main" java.lang.NullPointerException
- at TestDownLoadImage.imageDownLoad(TestDownLoadImage.java:72)
- 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
//Use it before URLConnection con = url.openConnection()
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import javax.net.ssl.HostnameVerifier;
- import javax.net.ssl.HttpsURLConnection;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLSession;
- import javax.net.ssl.TrustManager;
- import javax.net.ssl.X509TrustManager;
- public class SslUtils {
- public static void trustAllHttpsCertificates() throws Exception {
- TrustManager[] trustAllCerts = new TrustManager[1];
- TrustManager tm = new miTM();
- trustAllCerts[0] = tm;
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, trustAllCerts, null);
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- }
- static class miTM implements TrustManager,X509TrustManager {
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- public boolean isServerTrusted(X509Certificate[] certs) {
- return true;
- }
- public boolean isClientTrusted(X509Certificate[] certs) {
- return true;
- }
- public void checkServerTrusted(X509Certificate[] certs, String authType)
- throws CertificateException {
- return;
- }
- public void checkClientTrusted(X509Certificate[] certs, String authType)
- throws CertificateException {
- return;
- }
- }
- /**
- * The SSL certificate that ignores the HTTPS request must be invoked before openConnection
- * @throws Exception
- */
- public static void ignoreSsl() throws Exception{
- HostnameVerifier hv = new HostnameVerifier() {
- public boolean verify(String urlHostName, SSLSession session) {
- return true;
- }
- };
- trustAllHttpsCertificates();
- HttpsURLConnection.setDefaultHostnameVerifier(hv);
- }
- }
- public static void main(String[] args) {
- //String url="http://wx1.sinaimg.cn/mw690/006sl6kBgy1fel3aq0nyej30i20hxq7i.jpg";
- String url="https://05.imgmini.eastday.com/mobile/20170413/20170413053046_4a5e70ed0b39c824517630e6954861f2_1.jpeg";
- String downToFilePath="d:/download/image/";
- String fileName="test";
- try {
- SslUtils.ignoreSsl();
- } catch (Exception e) {
- e.printStackTrace();
- }
- imageDownLoad(url, downToFilePath,fileName);
- }