java:URLConnection后台下载文件&设置代理

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


前言

java后台程序URLConnection下载文件&设置代理
​参考文章:让URLConnection使用代理服务器​​参考文章:根据文件的url在网络上下载文件

代码

//存储位置
private static String sumPath = "./oosfile/";
//读取大小
private static int BSIZE = 1024;

/**
* 所需的URL等信息
* @param map
*/
public void czhAddData2(Map<String, String> map) {
//输入输出流
FileOutputStream out = null;
InputStream ins = null;
try {
//设置系统代理 不需要的省略
Properties prop = System.getProperties();
prop.put("http.proxyHost", "127.0.0.1");
prop.put("http.proxyPort", "8088");
//下载路径
URL url = new URL(map.get("url"));
URLConnection con = url.openConnection();
File dir = new File(sumPath);
if (!dir.exists()) {
dir.mkdirs();
}
//文件位置
out = new FileOutputStream(sumPath+now+".txt");
int contentLength = con.getContentLength();
if(contentLength>0){
// 创建缓冲区
byte[] buffer = new byte[BSIZE];
ins = con.getInputStream();
//写入
while (ins.read(buffer) != -1) {
out.write(buffer);
out.flush();
}
}

}catch (IOException e){
throw new RuntimeException(e);
} finally {
try {
ins.close();
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}

}

延伸

​​urlconnection.connect()和url.openconnection()的区别​​


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java