2024-07-03 16:11:21 +08:00

219 lines
6.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.zhgd.xmgl.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* @author 邱平毅
* @ClassName UploadUtil
* @date 2022/8/26 12:40
* @Version 1.0
*/
@Slf4j
public class UrlUtil {
private UrlUtil() {
}
// 通过Url将图片转为MultipartFile
public static MultipartFile uploadImgUrlToMultipartFile(String url) {
byte[] bytes = downloadPicture(url);
String name = "imageFile.png";
MultipartFile multipartFile = getMultipartFile(name, bytes);
return multipartFile;
}
/**
* 获取图片二进制
*/
public static byte[] downloadPicture(String url) {
URL urlConnection = null;
HttpURLConnection httpURLConnection = null;
try {
urlConnection = new URL(url);
httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
InputStream in = httpURLConnection.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
return out.toByteArray();
} catch (Exception e) {
log.error("error", e);
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return null;
}
/**
* 通过URL获取文件inputStream
*/
public static InputStream getInputStream(String url) {
URL urlConnection = null;
HttpURLConnection httpURLConnection = null;
try {
urlConnection = new URL(url);
httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
return httpURLConnection.getInputStream();
} catch (Exception e) {
log.error("error", e);
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
log.error("URL文件上传时返回为空");
return null;
}
// 二进制文件转换MultipartFile
public static MultipartFile getMultipartFile(String name, byte[] bytes) {
MultipartFile mfile = null;
ByteArrayInputStream in = null;
try {
in = new ByteArrayInputStream(bytes);
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
mfile = new CommonsMultipartFile(fileItem);
in.close();
} catch (Exception e) {
log.error("error", e);
return null;
}
return mfile;
}
/**
* 在给定的url后面拼接查询参数
*
* @param baseUrl url地址
* @param params 要拼接的查询参数map
* @return 拼接上params查询参数的新url
*/
public static String urlJoin(String baseUrl, Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return baseUrl;
}
StringBuilder sb = new StringBuilder(baseUrl);
boolean isFirst = true;
Map<String, String> spMap = urlSplit(baseUrl);
for (Object key : params.keySet()) {
String value = String.valueOf(params.get(key));
if (key != null && StringUtils.isNotEmpty(value)) {
if (isFirst && spMap.isEmpty()) {
isFirst = false;
sb.append("?");
} else {
sb.append("&");
}
sb.append(key).append("=").append(value);
}
}
return sb.toString();
}
/**
* 去掉url中的路径留下请求参数部分
* 例https://postest.bgzchina.com/mobilePay?sysId=ZDM20210510000088857537去掉后
* sysId=ZDM20210510000088857537
*
* @param strURL url地址
* @return url请求参数部分
*/
private static String truncateUrlPage(String strURL) {
String strAllParam = null;
String[] arrSplit = null;
strURL = strURL.trim().toLowerCase();
arrSplit = strURL.split("[?]");
if (strURL.length() > 1) {
if (arrSplit.length > 1) {
for (int i = 1; i < arrSplit.length; i++) {
strAllParam = arrSplit[i];
}
}
}
return strAllParam;
}
/**
* 解析出url参数中的键值对
* 如 "index.jsp?Action=del&id=123"解析出Action:del,id:123存入map中
*
* @param URL url地址
* @return url请求参数部分
*/
public static Map<String, String> urlSplit(String URL) {
Map<String, String> mapRequest = new HashMap<>(16);
String[] arrSplit = null;
String strUrlParam = truncateUrlPage(URL);
if (strUrlParam == null) {
return mapRequest;
}
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
//解析出键值
if (arrSplitEqual.length > 1) {
//正确解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
//只有参数没有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
/**
* 保存图片到本地
*
* @param url
* @param savePath
* @param fileName
* @return
*/
public static String saveToLocal(String url, String savePath, String fileName) {
if (StringUtils.isBlank(url)) {
return null;
}
try {
X509TrustManagerUtil.downLoadFromUrl(url, fileName, savePath);
} catch (Exception e) {
log.error("下载图片出现异常:" + e);
return null;
}
return fileName;
}
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>(16);
map.put("k1", "v1");
map.put("k", "v");
System.out.println(urlJoin("http://baidu.com", map));
}
}