import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.util.Scanner;
import javax.net.ssl.SSLContext;
public class DownLoaderV1 {
public static void main(String[] args) throws IOException, GeneralSecurityException {
System.out.println("java.class.path : "+System.getProperty("java.class.path"));
String p = System.getProperty("java.class.path");//获取当前类的路径
String path = p.replace("\\","\\\\");//将获取的路径字符串改为JAVA可用的路径格式。
Scanner sc = new Scanner(System.in);
System.out.println("请输入url网址:");
String url = sc.nextLine();
System.out.println("将文件存储为(文件名):");
String filename = sc.nextLine();
DownLoad(filename,url,path);
}
public static void DownLoad(String filename,String url,String path) throws IOException, GeneralSecurityException{
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null,null,null);
SSLContext.setDefault(sslContext); //指定协议版本为TLSv1.2版本
URL u = new URL(url);
URLConnection uconn = u.openConnection();
//String path = Class.class.getClass().getResource("/").getPath();//获取当前类的路径
BufferedInputStream bis = new BufferedInputStream(uconn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path+"\\"+filename));
byte[] b = new byte[1024];
int len = 0;
while((len = bis.read(b))!=-1){
bos.write(b,0,len);
bos.flush();
}
bis.close();
bos.close();
System.out.println("下载成功!");
}
}
注:如果出现Exception in thread “main” javax.net.ssl.SSLException: Received fatal alert: protocol_version类似的错误,那么很有可能是有可能就是服务端和请求端协议版本不一致导致的,通过指定协议版本来解决。