java version "1.8.0_172"
package com.lisx.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* 李双喜下载https图片
*/
public class DownLoadPic {
public static void main(String[] args) {
// 图片地址
String strUrl = "https://img-blog.csdnimg.cn/8e1a4b188ba64d76b205ff389aa6ef4e.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NzZG5uZXdz,size_16,color_FFFFFF,t_70#pic_center";
downloadImg(strUrl, "D:\\李双喜", "1.png");
String strut2 ="https://bkimg.cdn.bcebos.com/pic/b64543a98226cffcdb72b311bb014a90f603ea3d?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2U5Mg==,g_7,xp_5,yp_5/format,f_auto";
downloadImg(strut2, "D:\\李双喜", "2.jpg");
}
/**
* 抓取网上的图片x
*
*/
public static void downloadImg(String imgSrc, String filePath, String fileName) {
try {
URL url = new URL(imgSrc);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream str = conn.getInputStream();
byte[] bs = new byte[1024];
int len = 0;
File saveDir = new File(filePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream out = new FileOutputStream(file);
while ((len = str.read(bs)) != -1) {
out.write(bs, 0, len);
}
out.flush();
out.close();
str.close();
System.out.println("下载成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}