使用Java从HTTPS服务器下载文件 [英] Download file from HTTPS server using Java

查看:137
本文介绍了使用Java从HTTPS服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从使用安全连接协议HTTPS的服务器下载文件。我可以在普通服务器上做,但是,我怎么能用HTTPS做到这一点。如果有人使用过示例API,请帮我找到有用的资源。

I want to download a file from the server which is using the secured connection protocol HTTPS. I could do it in the normal server, But, how I can do it using the HTTPS. If anyone have used the sample API, please help me to find the useful resources.

推荐答案

使用Java访问HTTPS网址是然后访问HTTP网址。您始终可以使用

Access an HTTPS url with Java is the same then access an HTTP url. You can always use the

URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file

但是,你可以遇到一些问题服务器的证书链无法验证。
因此,您可能需要为测试目的禁用证书验证并信任所有证书。

But, you can have some problem when the server's certificate chain cannot be validated. So you may need to disable the validation of certificates for testing purposes and trust all certificates.

为此,请写下:

// Create a new trust manager that trust all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Activate the new trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// And as before now you can use URL and URLConnection
URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file

这篇关于使用Java从HTTPS服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆