Http / Https 下载文件,startWith不能验证https,测试地址:https://storage.googleapis.com/golang/go1.7.3.windows-amd64.msi
java
private static final Logger logger = Logger.
getLogger(MethodHandles.lookup().lookupClass());
private static void sunNetSsl() {
System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
}
private static void javaxNetSsl(){
TrustManager[] trustAllCertArr = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[]
certArr,String authType) throws CertificateException {}
public void checkClientTrusted(X509Certificate[]
certArr,String authType) throws CertificateException {}
}};
//activate trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null,trustAllCertArr,new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
public static void download(String downloadUrl,String fileName,boolean isHttps) throws IOException{
if (isHttps) {
logger.info(isHttps);
javaxNetSsl();
//sunNetSsl();
}
URL url = new URL(downloadUrl);
try(ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(fileName)){
fos.getChannel().transferFrom(rbc,0,Long.MAX_VALUE);
}catch(IOException e){
e.printStackTrace();
}
}