hutool HttpUtil
okhttp
//import java.net.URL;
//import java.net.URLConnection;
public void download() {
String downLoadUrl = "<https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png>";
try {
// 构造URL
URL url = new URL(downLoadUrl);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
//图片的完整路径
String filename = "D:/a/b/1.jpg";
// 输出的文件流
File file = new File(filename);
//是否存在目录
isChartPathExist("D:/a/b/");
FileOutputStream os = new FileOutputStream(file, true);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//java判断指定路径文件夹是否存在,若不存在则创建新的文件夹
private static void isChartPathExist(String dirPath) {
File file = new File(dirPath);
if (!file.exists()) {
file.mkdirs();
}
}