Download file from HTTPS server using Java(使用 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 url和访问HTTP url是一样的.您可以随时使用
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 服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Java 从 HTTPS 服务器下载文件
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01