JAVA 小练习-3 迷你下载器改进(设置存储路径默认为当前类的所在路径,并指定TLS版本)

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类似的错误,那么很有可能是有可能就是服务端和请求端协议版本不一致导致的,通过指定协议版本来解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值