java - 如何在JAVA中从HTTPS url保存文件?

标签 java https httpurlconnection outputstream filepicker.io

我正在尝试使用输出流从 URL 保存文件。 URL 通过 https 进行安全保护。因此,当我尝试获取如下文件时出现一些错误

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 sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at java.net.URL.openStream(Unknown Source) 
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 60 more

假设我想从此 URL 打开文件

https://www.filepicker.io/api/file/KW9EJhYtS6y48Whm2S6D?signature=4098f262b9dba23e4766ce127353aaf4f37fde0fd726d164d944e031fd862c18&policy=eyJoYW5kbGUiOiJLVzlFSmhZdFM2eTQ4V2htMlM2RCIsImV4cGlyeSI6MTUwODE0MTUwNH0=

所以我做了类似的事情:

try{    
    URL URL = new URL('https://www.filepicker.io/api/file/KW9EJhYtS6y48Whm2S6D?signature=4098f262b9dba23e4766ce127353aaf4f37fde0fd726d164d944e031fd862c18&policy=eyJoYW5kbGUiOiJLVzlFSmhZdFM2eTQ4V2htMlM2RCIsImV4cGlyeSI6MTUwODE0MTUwNH0=');
    String = path = "D://download/";
    InputStream ins = url.openStream();
    OutputStream ous = new FileOutputStream(path);
    final byte[] b = new byte[2048];
    int length;

        while ((length = inputStream.read(b)) != -1) {
               ous.write(b, 0, length);
         }

           ins.close();
           ous.close();
}

结果在专用Floder中没有发生任何事情,因为显示了错误。如何从 HTTPS url 获取文件?

最佳答案

HTTPS 连接需要握手。 IE。明确地承认对方。服务器已通过 HTTPS 证书标识自身,但您的信任存储中显然没有此证书,而且 Java 代码中也没有明确确认该标识,因此 HttpsURLConnection (正在使用此处在幕后使用)拒绝继续 HTTPS 请求。

作为启动示例,您可以在类中使用以下代码片段,让 HttpsURLConnection 接受所有 SSL 证书,无论您使用什么 HTTPS URL。

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);
    }
}

但是,如果您希望对每个证书进行更细粒度的控制,请按照 their Javadoc 相应地实现这些方法。 .

<小时/>

与具体问题无关,您的代码中还有第二个问题。您正在尝试将下载的文件保存为文件夹而不是文件。

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

除了语法错误更可能是在提出问题时粗心造成的(即直接编辑有问题的代码而不是实际复制粘贴工作代码)之外,这没有任何意义。您不应指定文件夹作为保存位置。您应该指定一个文件名。如果需要,您可以从 Content-Disposition header 中提取它,或者使用 File#createTempFile() 自动生成一个 header 。例如

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

(如果您已经使用 Java 7,只需使用 Files#copy() 而不是该样板文件)

关于java - 如何在JAVA中从HTTPS url保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18576069/

相关文章:

Java读写高分

java - 创建库并使用 sbt 进行测试时设置 scala 断点

java - 如何使用 Jersey Client 为每个 POST 请求建立新连接

apache - 迁移到 https(网站 + KeyCDN)后 htaccess 出现问题

java - 第二次打开同一连接时,HttpUrlConnection.getOutputStream 导致 "Handshake message sequence violation, 11"异常

java - Docker Ubuntu 主机上的 jni4net

java - HttpsURLConnections 默认主机名 validator

java - HttpURLConnection - 响应代码 : 400 (Bad Request) Android Studio -> xserve

android - 有什么方法可以使用 HttpUrlConnection 正确获取上传进度

java - 没有这样的表 : Error in android