使用Java从HTTPS服务器下载文件
我想从使用安全连接协议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 certificatesTrustManager[] 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服务器下载文件 的全部内容, 来源链接: utcz.com/qa/399951.html