<分区>
我想从使用安全连接协议(protocol) HTTPS 的服务器下载文件。我可以在普通服务器上做到这一点,但是,我如何使用 HTTPS 做到这一点。如果有人使用过示例 API,请帮助我找到有用的资源。
<分区>
我想从使用安全连接协议(protocol) HTTPS 的服务器下载文件。我可以在普通服务器上做到这一点,但是,我如何使用 HTTPS 做到这一点。如果有人使用过示例 API,请帮助我找到有用的资源。
最佳答案
使用 Java 访问 HTTPS url 与访问 HTTP url 相同。您可以随时使用
URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file
但是,当无法验证服务器的证书链时,您可能会遇到一些问题。 因此,出于测试目的,您可能需要禁用证书验证并信任所有证书。
为此写:
// 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 - 使用 Java 从 HTTPS 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135074/