通过https下载文件到指定路径
java
public static void downloadFile(String urlString, String pathName) {
try{
try {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{
new javax.net.ssl.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) {
}
}
};
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
javax.net.ssl.HostnameVerifier allHostsValid = new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return true;
}
};
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (java.security.NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (java.security.KeyManagementException e) {
e.printStackTrace();
}
java.net.URL url = new java.net.URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(60*1000);
conn.setReadTimeout(5*60*1000);
conn.connect();
try {
java.nio.channels.ReadableByteChannel rbChannel = java.nio.channels.Channels.newChannel(
conn.getInputStream()
);
java.io.FileOutputStream fs = new java.io.FileOutputStream(pathName);
java.nio.channels.FileChannel chan = fs.getChannel();
while (chan.transferFrom(rbChannel, 0, Long.MAX_VALUE)>0){};
chan.force(false);
chan.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
} catch(java.net.MalformedURLException e){
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}