package com.lj.mc.preview.utils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.hst.mc.preview.config.ConstantsConfig;
import com.hst.mc.preview.model.FileAttribute;
import com.hst.mc.preview.model.ReturnResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import lombok.extern.slf4j.Slf4j;
/**
* 下载工具类,从远端通过http或着ftp连接下载文件到本地
*
* @author lj
* @author yudian-it
* @date 2021/09/06
*/
@Slf4j
public class DownloadUtils {
private static final String URL_PARAM_FTP_USERNAME = "ftp.username";
private static final String URL_PARAM_FTP_PASSWORD = "ftp.password";
private static final String URL_PARAM_FTP_CONTROL_ENCODING = "ftp.control.encoding";
/**
* @param fileAttribute fileAttribute
* @param fileName 文件名
* @return 本地文件绝对路径
*/
public static ReturnResponse<String> downLoad(FileAttribute fileAttribute, String fileName) {
final String normalizeUrlStr = URLUtil.normalize(fileAttribute.getUrl());
URLEncoder urlEncoder = URLEncoder.createDefault();
urlEncoder.addSafeCharacter('?');
URL url = transUrl(urlEncoder.encode(normalizeUrlStr, CharsetUtil.CHARSET_UTF_8));
String realPath = DownloadUtils.getRelFilePath(fileName, fileAttribute);
try {
if (KkFileUtils.isHttpUrl(url)) {
log.info("准备下载远程HTTP文件到本地, realPath:{},url:{}", realPath, url);
FileUtil.writeFromStream(url.openStream(), realPath);
} else if (KkFileUtils.isFtpUrl(url)) {
String ftpUsername = WebUtils.getUrlParameterReg(fileAttribute.getUrl(), URL_PARAM_FTP_USERNAME);
String ftpPassword = WebUtils.getUrlParameterReg(fileAttribute.getUrl(), URL_PARAM_FTP_PASSWORD);
String ftpControlEncoding = WebUtils.getUrlParameterReg(fileAttribute.getUrl(),
URL_PARAM_FTP_CONTROL_ENCODING);
log.info("准备下载远程FTP文件到本地, realPath:{},url:{}", realPath, url);
FtpUtils.download(fileAttribute.getUrl(), realPath, ftpUsername, ftpPassword, ftpControlEncoding);
} else {
String errorMsg = StrUtil.format("不能识别url:{}", normalizeUrlStr);
log.error(errorMsg);
return ReturnResponse.failure(errorMsg);
}
return ReturnResponse.success(realPath);
} catch (Exception ex) {
String errorMsg = "文件下载异常:";
if (ex instanceof FileNotFoundException) {
errorMsg += "文件不存在";
} else {
errorMsg += "其他异常";
}
log.error(errorMsg, ex);
return ReturnResponse.failure(errorMsg);
}
}
private static URL transUrl(String urlStr) {
//用于高版本JDK跳过证书验证
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Activate the new trust manager
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//用于校验SSL 的IP
HostnameVerifier allHostsValid = (hostname, session) -> true;
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// Open connection to the URL
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
return connection.getURL();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 获取真实文件绝对路径
*
* @param fileName 文件名
* @return 文件路径
*/
public static String getRelFilePath(String fileName, FileAttribute fileAttribute) {
String type = fileAttribute.getSuffix();
if (null == fileName) {
UUID uuid = UUID.randomUUID();
fileName = uuid + "." + type;
} else { // 文件后缀不一致时,以type为准(针对simText【将类txt文件转为txt】)
fileName = fileName.replace(fileName.substring(fileName.lastIndexOf(".") + 1), type);
}
String realPath = ConstantsConfig.getFileDir() + fileName;
File dirFile = new File(ConstantsConfig.getFileDir());
if (!dirFile.exists() && !dirFile.mkdirs()) {
log.error("创建目录【{}】失败,可能是权限不够,请检查", ConstantsConfig.getFileDir());
}
log.info("获取真实文件绝对路径, filePath:{}", realPath);
return realPath;
}
}
下载工具类
最新推荐文章于 2024-01-23 08:45:51 发布