通过java通过https下载文件

发布于 2024-08-01 14:56:44 字数 4383 浏览 2 评论 0原文

这是我现在从网上复制的代码,

/**
 * A simple example that uses HttpClient to perform a GET using Basic
 * Authentication. Can be run standalone without parameters.
 *
 * You need to have JSSE on your classpath for JDK prior to 1.4
 *
 * @author Michael Becke
 */
public class BasicAuthenticationExample {

    /**
     * Constructor for BasicAuthenticatonExample.
     */
    public BasicAuthenticationExample() {
        super();
    }

    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();

       client.getState().setCredentials(
                new AuthScope("login.website.com", 443),
                new UsernamePasswordCredentials("login id", "password")
                );

        GetMethod get = new GetMethod(
                "https://url to the file");

        get.setDoAuthentication( true );

        try {
            // execute the GET
            int status = client.executeMethod( get );

            // print the status and response
            System.out.println(status + "\n" + 
                    get.getResponseBodyAsString());

        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }
}

            int status = client.executeMethod( get );

因为我收到以下错误的

Exception in thread "main" 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(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at BasicAuthenticationExample.main(BasicAuthenticationExample.java:38)
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(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 18 more
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)
... 24 more

现在,此错误的原因当然是我的服务器发送的证书尚未在我的受信任证书列表中。 我的问题是如何将证书放入受信任列表。

谢谢 普拉纳贝什

Here is a code that I copied from the web

/**
 * A simple example that uses HttpClient to perform a GET using Basic
 * Authentication. Can be run standalone without parameters.
 *
 * You need to have JSSE on your classpath for JDK prior to 1.4
 *
 * @author Michael Becke
 */
public class BasicAuthenticationExample {

    /**
     * Constructor for BasicAuthenticatonExample.
     */
    public BasicAuthenticationExample() {
        super();
    }

    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();

       client.getState().setCredentials(
                new AuthScope("login.website.com", 443),
                new UsernamePasswordCredentials("login id", "password")
                );

        GetMethod get = new GetMethod(
                "https://url to the file");

        get.setDoAuthentication( true );

        try {
            // execute the GET
            int status = client.executeMethod( get );

            // print the status and response
            System.out.println(status + "\n" + 
                    get.getResponseBodyAsString());

        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }
}

now because of the line

            int status = client.executeMethod( get );

I get the following error

Exception in thread "main" 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(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at BasicAuthenticationExample.main(BasicAuthenticationExample.java:38)
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(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 18 more
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)
... 24 more

Now the reason for this error is of course that the certificate sent by my server is not already in my list of trusted certificates.
My question is how to get the certificate into the trusted list.

Thanks
Pranabesh

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我恋#小黄人 2024-08-08 14:56:44

您将需要一个包含要信任的证书的密钥库。 您可以使用Java的 keytool 命令来执行那。 有几种方法可以做到这一点:

  • 将其添加到默认的 Java 密钥库(Windows 上的主目录或用户目录中的 .keystore
  • 设置系统属性 javax.net.ssl.trustStore 到备用密钥库的位置(例如 java -Djavax.net.ssl.trustStore=/path/to/keystore
  • 构建您自己的 SSLSocketFactory 实现可以以任何您想要的方式加载密钥库(此绝对是最复杂的)

密钥库只是一个包含可用于各种用途的密钥和/或证书的文件,在本例中是您的应用程序需要信任的证书。 Keytool 的使用方式如下:

keytool -importcert -file /path/to/certificate/file -keystore /path/to/keystore

对于其他命令行选项,只需运行

keytool -help

You will need a keystore that contains the certificate to trust. You can use Java's keytool command to do that. There are a few ways to do this:

  • Add it to the default Java keystore (.keystore in your home directory or user directory on Windows)
  • Set the system property javax.net.ssl.trustStore to the location of an alternate keystore (something like java -Djavax.net.ssl.trustStore=/path/to/keystore)
  • Build your own SSLSocketFactory implementation that can load a keystore any way you want (this is definitely the most complicated)

A keystore is just a file that contains keys and/or certificates that can be used for various things, in this case a certificate that your application will need to trust. Keytool can be used as follows:

keytool -importcert -file /path/to/certificate/file -keystore /path/to/keystore

For other command-line options, just run

keytool -help
晨光如昨 2024-08-08 14:56:44

您可以使用 keytool 导入。

You can use keytool import.

甜味拾荒者 2024-08-08 14:56:44

此页面似乎回答了您的问题:
将证书添加到您的 Java 密钥库

它引用了 Andres Sterbenz 的 InstallCert & 说明博客文章

如果证书仅用于测试,您可能不想实际将其添加到受信任的存储中。 所以你也可以 禁用证书验证

This page seems to answer your question:
Adding Certificates to your Java Keystore

It references Andres Sterbenz's InstallCert & explanation blog post.

You might not want to actually add the certificate in your trusted store, if it's only for testing. So you can also disable certificate validation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文