需求场景
链接如下:
https://i-blog.csdnimg.cn/blog_migrate/9e37d073237a59b3996c16f27ddba80a.png
此时需要通过发送请求将该图片下载到本地。
MountFile代码
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.**.pojo.MountInfo;
public class MountFile {
private static final Logger logger = LoggerFactory.getLogger(MountFile.class);
//图片存放路径
private final static String url_suffix = "data/image/";
public static String getRootPath() {
return rootPath;
}
public static String getQrRootPath(){
return qrRootPath;
}
public static String getQrUrlSuffix(){
return qr_url_suffix;
}
public static void mkDir(String filePath) {
File f;
f = new File(filePath);
if (!f.exists()) {
f.mkdirs();
}
}
/**
* 按时间划分目录
*
* @return
*/
public static String getDir() {
Calendar cl = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String date = dateFormat.format(cl.getTime());
String hour = cl.get(Calendar.HOUR) < 10 ? "0" + cl.get(Calendar.HOUR) : String.valueOf(cl.get(Calendar.HOUR));
String minute = cl.get(Calendar.MINUTE) < 10 ? "0" + cl.get(Calendar.MINUTE) : String.valueOf(cl
.get(Calendar.MINUTE));
String dir = date + "/" + hour + "/" + minute + "/";
return dir;
}
public static String getFileName(String fileType) {
return FileFactory.getInstance().getRandName() + fileType;
}
public static MountInfo getMountFullPath(String fileExt) {
String dirPath = getDir();
String fileName = getFileName(fileExt);
String imgUrl = "";
// 写入原图
mkDir(getRootPath() + dirPath);
String fullName = getRootPath() + dirPath + fileName;
imgUrl = url_suffix + dirPath + fileName;
if ("".equals(imgUrl)) {
logger.info("upload img failed");
}
MountInfo info = new MountInfo();
info.setFilePath(fullName);
info.setRelativeUrl(imgUrl);
String httpUrl = "https://img.**.com" + imgUrl;
info.setUrl(httpUrl);
return info;
}
}
FileFactory代码
import java.util.Calendar;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
public class FileFactory {
private static FileFactory instance;
private static String seed[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q","r","s","t", "u","v","w","x" };
private Random rand = new Random();
static {
instance = new FileFactory();
}
public static FileFactory getInstance() {
return instance;
}
public FileFactory() {
for (int i = 0; i < seed.length; i++) {
}
}
public String getRandName() {
int qid = rand.nextInt(seed.length);
Calendar cl = Calendar.getInstance();
String hour = cl.get(Calendar.HOUR) < 10 ? "0" + cl.get(Calendar.HOUR): String.valueOf(cl.get(Calendar.HOUR));
String minute = cl.get(Calendar.MINUTE) < 10 ? "0"+ cl.get(Calendar.MINUTE) : String.valueOf(cl.get(Calendar.MINUTE));
String suffix = RandomStringUtils.randomAlphanumeric(4);
return suffix+"_"+seed[qid] +seed[cl.get(Calendar.HOUR)]+seed[cl.get(Calendar.MINUTE) % 24]+qid+hour+minute ;
}
public String getPathByTime() {
return null;
}
}
MountInfo类的代码pojo
import com.alibaba.fastjson.JSONObject;
public class MountInfo {
private String filePath;//图片文件路径
private String relativeUrl;
private String url;//图片访问地址
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getRelativeUrl() {
return relativeUrl;
}
public void setRelativeUrl(String relativeUrl) {
this.relativeUrl = relativeUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
String mountInfoStr = JSONObject.toJSONString(this);
return mountInfoStr;
}
}
httpDownLoadImage类的代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.**.pojo.MountInfo;
import com.***.util.card.MountFile;
public class ImageUtil {
private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
/**
* 下载图片
* @param url
* @param path
*/
@SuppressWarnings("resource")
public static MountInfo httpDownLoadImage(String url) {
MountInfo mountInfo = new MountInfo();
String fullFilePath = "";
// 根据内容类型获取扩展名(已经带上了点号了)
String fileExt = getFileexpandedName("jpg");
// 将mediaId作为文件名
mountInfo = MountFile.getMountFullPath(fileExt);
fullFilePath = mountInfo.getFilePath();
InputStream inputStream = getInputStream(url);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileoutputStream = null;
try {
fileoutputStream = new FileOutputStream(new File(fullFilePath));
while ((len = inputStream.read(data)) != -1) {
fileoutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mountInfo;
}
/**
* 获取服务端的数据,以InputStream形式返回
* @return
*/
public static InputStream getInputStream(String urlPath) {
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlPath);
if (url != null) {
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置连接网络超时时间
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
// 表示设置本次http请求使用的GET方式请求
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
// 从服务器中获得一个输入流
inputStream = httpURLConnection.getInputStream();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
public static String getFileexpandedName(String contentType) {
String fileEndWitsh = "";
if ("image/jpeg".equals(contentType))
fileEndWitsh = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileEndWitsh = ".mp3";
else if ("audio/amr".equals(contentType))
fileEndWitsh = ".amr";
else if ("video/mp4".equals(contentType))
fileEndWitsh = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileEndWitsh = ".mp4";
else {
fileEndWitsh = ".jpg";
}
logger.info("fileEndWitsh={}", fileEndWitsh);
return fileEndWitsh;
}
public static void main(String[] args) {
//此处放入需要下载的图片地址即可
MountInfo httpDownLoadImage = ImageUtil.httpDownLoadImage("https://i-blog.csdnimg.cn/blog_migrate/9e37d073237a59b3996c16f27ddba80a.png");
System.out.println(httpDownLoadImage.toString());
}
}