How to save the file from HTTPS url in JAVA?

﹥>﹥吖頭↗ 提交于 2019-12-03 00:52:13

A HTTPS connection requires handshaking. I.e. explicitly acknowledge each other. The server has identified itself by a HTTPS certificate, but you apparently don't have this certificate in your trust store and you are nowhere in your Java code explicitly acknowledging the identification, so the HttpsURLConnection (which is being used under the covers here) refuses to continue the HTTPS request.

As a kickoff example, you can use the following piece of code in your class to let HttpsURLConnection accept all SSL certificates, regardless of the HTTPS URL you use.

static {
    final TrustManager[] trustAllCertificates = new TrustManager[] {
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null; // Not relevant.
            }
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
        }
    };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        throw new ExceptionInInitializerError(e);
    }
}

If you however want more fine grained control on a per-certificate basis, then implement the methods accordingly as per their Javadoc.


Unrelated to the concrete problem, you've a second problem in your code. You're attempting to save it the downloaded file as a folder instead of as a file.

String = path = "D://download/";
OutputStream ous = new FileOutputStream(path);

Apart from the syntax error which is more likely result of carelessness during formulating the question (i.e. editing the code straight in question instead of actually copypasting working code), this isn't making any sense. You should not specify a folder as save location. You should specify a file name. You can if necessary extract it from the Content-Disposition header, or autogenerate one with File#createTempFile(). E.g.

File file = File.createTempFile("test-", ".jpg", new File("D:/download/"));
Files.copy(url.openStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);

(and if you're already on Java 7, just make use of Files#copy() instead of that boilerplate)

The cause of the error is that Java cannot confirm the validity of the certificate. This can be fixed by importing the certificate into the JAVA certificate storage, or "fixed" by disabling SSL certificate validation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!