项目构建
This commit is contained in:
54
demo-common/demo-common-utils/pom.xml
Normal file
54
demo-common/demo-common-utils/pom.xml
Normal file
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.yxt.demo</groupId>
|
||||
<artifactId>demo-common</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>demo-common-utils</artifactId>
|
||||
<version>0.0.1</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!--okhttp-->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
</dependency>
|
||||
<!--jwt-->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-beanutils</groupId>
|
||||
<artifactId>commons-beanutils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.yxt.demo.common.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2022/2/9 21:52
|
||||
* @Description 工具类
|
||||
*/
|
||||
public class BeanUtils {
|
||||
|
||||
|
||||
/**
|
||||
* 获取String 类型
|
||||
*
|
||||
* @param map
|
||||
* @param keyName 键值对中键名称
|
||||
* @param defaultValue 默认值
|
||||
* @return
|
||||
*/
|
||||
public static String getString(Map<String, Object> map, String keyName, String defaultValue) {
|
||||
if (map == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (map.containsKey(keyName)) {
|
||||
Object o = map.get(keyName);
|
||||
if (o instanceof String) {
|
||||
return (String) o;
|
||||
} else {
|
||||
return defaultValue;
|
||||
}
|
||||
} else {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取Integer
|
||||
public static Integer getInteger(Map<String, Object> map, String keyName) {
|
||||
if (map == null) {
|
||||
return -1;
|
||||
}
|
||||
if (map.containsKey(keyName)) {
|
||||
Object o = map.get(keyName);
|
||||
if (o instanceof Integer) {
|
||||
return (int) o;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
//获取map类型
|
||||
public static Map<String, Object> getMap(Map<String, Object> map, String keyName) {
|
||||
if (map == null) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
if (map.containsKey(keyName)) {
|
||||
Object o = map.get(keyName);
|
||||
if (o instanceof Map) {
|
||||
return (Map) o;
|
||||
} else {
|
||||
return new HashMap<>();
|
||||
}
|
||||
|
||||
} else {
|
||||
return new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
// 获取List类型
|
||||
public static List<Map<String, Object>> getListData(Map<String, Object> map, String keyName) {
|
||||
List<Map<String, Object>> list = new ArrayList<>();
|
||||
if (map == null) {
|
||||
return list;
|
||||
}
|
||||
if (map.containsKey(keyName)) {
|
||||
Object o = map.get(keyName);
|
||||
if (o instanceof List) {
|
||||
for (int i = 0; i < ((List) o).size(); i++) {
|
||||
Object o1 = ((List) o).get(i);
|
||||
if (o1 instanceof Map) {
|
||||
list.add((Map) o1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.yxt.demo.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2022/6/21 0:03
|
||||
* @Description 校验参数工具
|
||||
*/
|
||||
public class ValidationUtil {
|
||||
|
||||
public final static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
|
||||
|
||||
/**
|
||||
* 验证单个实体
|
||||
*
|
||||
* @param t 参数
|
||||
* @param <T> 类型
|
||||
* @return 验证结果
|
||||
*/
|
||||
public static <T> String validateOne(T t) {
|
||||
Set<ConstraintViolation<T>> validateResult = validator.validate(t);
|
||||
if (validateResult != null && validateResult.size() != 0) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (ConstraintViolation<T> valid : validateResult) {
|
||||
sb.append(valid.getPropertyPath().toString()).append(StringUtils.SPACE).append(valid.getMessage())
|
||||
.append(",");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证多个实体
|
||||
*
|
||||
* @param ts 参数
|
||||
* @param <T> 类型
|
||||
* @return 验证结果
|
||||
*/
|
||||
public static <T> String validateMutil(List<T> ts) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int index = 0; index < ts.size(); ++index) {
|
||||
String validateOneResult = validateOne(ts.get(index));
|
||||
if (!StringUtils.isBlank(validateOneResult)) {
|
||||
sb.append("index[" + index + "]:").append(validateOneResult).append(";");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.yxt.demo.common.utils.allutils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2022/7/23 23:59
|
||||
* @Description
|
||||
*/
|
||||
@Slf4j
|
||||
public class RegexpUtils {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.yxt.demo.common.utils.captcha;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2021/11/6 21:58
|
||||
* @Description
|
||||
*/
|
||||
public class ImageUtils {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.yxt.demo.common.utils.convert;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2022/7/23 23:38
|
||||
* @Description
|
||||
*/
|
||||
public class StringUtil extends StringUtils {
|
||||
|
||||
/**
|
||||
* 空字符串
|
||||
*/
|
||||
private static final String NULLSTR = "";
|
||||
|
||||
/**
|
||||
* 下划线
|
||||
*/
|
||||
private static final char SEPARATOR = '_';
|
||||
|
||||
/**
|
||||
* 星号
|
||||
*/
|
||||
private static final String START = "*";
|
||||
|
||||
/**
|
||||
* * 判断一个Collection是否为空, 包含List,Set,Queue
|
||||
*
|
||||
* @param coll 要判断的Collection
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Collection<?> coll) {
|
||||
return isNull(coll) || coll.isEmpty();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否为空
|
||||
*
|
||||
* @param object Object
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isNull(Object object) {
|
||||
return object == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
|
||||
*
|
||||
* @param str 指定字符串
|
||||
* @param strs 需要检查的字符串数组
|
||||
* @return 是否匹配
|
||||
*/
|
||||
public static boolean matchesTwo(String str, List<String> strs) {
|
||||
if (isEmpty(str) || isEmpty(strs)) {
|
||||
return false;
|
||||
}
|
||||
for (String testStr : strs) {
|
||||
if (matchesTwo(str, testStr)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean matches(String str, List<String> strs) {
|
||||
if (isEmpty(str) || isEmpty(strs)) {
|
||||
return false;
|
||||
}
|
||||
for (String testStr : strs) {
|
||||
if (matches(str, testStr)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean matches(String str, String pattern) {
|
||||
if (isEmpty(pattern) || isEmpty(str)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
pattern = pattern.replaceAll("\\s*", ""); // 替换空格
|
||||
int beginOffset = 0; // pattern截取开始位置
|
||||
int formerStarOffset = -1; // 前星号的偏移位置
|
||||
int latterStarOffset = -1; // 后星号的偏移位置
|
||||
|
||||
String remainingURI = str;
|
||||
String prefixPattern = "";
|
||||
String suffixPattern = "";
|
||||
|
||||
boolean result = false;
|
||||
do {
|
||||
formerStarOffset = indexOf(pattern, START, beginOffset);
|
||||
prefixPattern = substring(pattern, beginOffset, formerStarOffset > -1 ? formerStarOffset : pattern.length());
|
||||
|
||||
// 匹配前缀Pattern
|
||||
result = remainingURI.equals(prefixPattern);
|
||||
// 已经没有星号,直接返回
|
||||
if (formerStarOffset == -1) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 匹配失败,直接返回
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
if (!isEmpty(prefixPattern)) {
|
||||
remainingURI = substringAfter(str, prefixPattern);
|
||||
}
|
||||
|
||||
// 匹配后缀Pattern
|
||||
latterStarOffset = indexOf(pattern, START, formerStarOffset + 1);
|
||||
suffixPattern = substring(pattern, formerStarOffset + 1, latterStarOffset > -1 ? latterStarOffset : pattern.length());
|
||||
|
||||
result = remainingURI.equals(suffixPattern);
|
||||
// 匹配失败,直接返回
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
if (!isEmpty(suffixPattern)) {
|
||||
remainingURI = substringAfter(str, suffixPattern);
|
||||
}
|
||||
|
||||
// 移动指针
|
||||
beginOffset = latterStarOffset + 1;
|
||||
|
||||
}
|
||||
while (!isEmpty(suffixPattern) && !isEmpty(remainingURI));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定字符串是否匹配
|
||||
*
|
||||
* @param str 指定字符串
|
||||
* @param pattern 需要检查的字符串
|
||||
* @return 是否匹配
|
||||
*/
|
||||
public static boolean matchesTwo(String str, String pattern) {
|
||||
if (isEmpty(pattern) || isEmpty(str)) {
|
||||
return false;
|
||||
}
|
||||
pattern = pattern.replaceAll("\\s*", ""); // 替换空格
|
||||
int beginOffset = 0; // pattern截取开始位置
|
||||
int formerStarOffset = -1; // 前星号的偏移位置
|
||||
int latterStarOffset = -1; // 后星号的偏移位置
|
||||
|
||||
String remainingURI = str;
|
||||
String prefixPattern = "";
|
||||
String suffixPattern = "";
|
||||
|
||||
boolean result = false;
|
||||
do {
|
||||
formerStarOffset = indexOf(pattern, START, beginOffset);
|
||||
prefixPattern = substring(pattern, beginOffset, formerStarOffset > -1 ? formerStarOffset : pattern.length());
|
||||
|
||||
// 匹配前缀Pattern
|
||||
result = remainingURI.contains(prefixPattern);
|
||||
// 已经没有星号,直接返回
|
||||
if (formerStarOffset == -1) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 匹配失败,直接返回
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
if (!isEmpty(prefixPattern)) {
|
||||
remainingURI = substringAfter(str, prefixPattern);
|
||||
}
|
||||
|
||||
// 匹配后缀Pattern
|
||||
latterStarOffset = indexOf(pattern, START, formerStarOffset + 1);
|
||||
suffixPattern = substring(pattern, formerStarOffset + 1, latterStarOffset > -1 ? latterStarOffset : pattern.length());
|
||||
|
||||
result = remainingURI.contains(suffixPattern);
|
||||
// 匹配失败,直接返回
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
if (!isEmpty(suffixPattern)) {
|
||||
remainingURI = substringAfter(str, suffixPattern);
|
||||
}
|
||||
|
||||
// 移动指针
|
||||
beginOffset = latterStarOffset + 1;
|
||||
}
|
||||
while (!isEmpty(suffixPattern) && !isEmpty(remainingURI));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.yxt.demo.common.utils.date;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2021/11/7 11:58
|
||||
* @Description 关于日期处理工具类
|
||||
*/
|
||||
public class DateUtils {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
//时间格式字符串转换成Date类型
|
||||
Date date = dateStrConvertDateCst("2021-11-07 12:28:20", "yyyy-MM-dd HH:mm:ss");
|
||||
//获取两个时间间隔的x天x小时x分钟
|
||||
System.out.println(getDatePoor(date, new Date()));
|
||||
//将Date类型转换成字符串类型
|
||||
System.out.println(dateConvertStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个时间间隔的x天x小时x分钟
|
||||
*
|
||||
* @param endDate 结尾时间
|
||||
* @param nowDate 当前时间
|
||||
* @return
|
||||
*/
|
||||
public static String getDatePoor(Date endDate, Date nowDate) {
|
||||
long nd = 1000 * 24 * 60 * 60;
|
||||
long nh = 1000 * 60 * 60;
|
||||
long nm = 1000 * 60;
|
||||
long ns = 1000;
|
||||
// 获得两个时间的毫秒时间差异
|
||||
long diff = endDate.getTime() - nowDate.getTime();
|
||||
// 计算差多少天
|
||||
long day = diff / nd;
|
||||
// 计算差多少小时
|
||||
long hour = diff % nd / nh;
|
||||
// 计算差多少分钟
|
||||
long min = diff % nd % nh / nm;
|
||||
// 计算差多少秒
|
||||
long s = diff % nd % nh % nm / ns;
|
||||
// 输出结果
|
||||
return day + "天" + hour + "小时" + min + "分钟" + s + "秒";
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间格式字符串转换成Date类型
|
||||
*
|
||||
* @param date 时间字符串
|
||||
* @param format 如:yyyy-MM-dd HH:mm:ss
|
||||
* @return
|
||||
*/
|
||||
public static Date dateStrConvertDateCst(String date, String format) {
|
||||
try {
|
||||
SimpleDateFormat simpledateformat = new SimpleDateFormat(format,
|
||||
Locale.US);
|
||||
Date newDate = simpledateformat.parse(date);
|
||||
return newDate;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Date类型转换成字符串类型
|
||||
*
|
||||
* @param date 时间
|
||||
* @param format 格式
|
||||
* @return
|
||||
*/
|
||||
public static String dateConvertStr(Date date, String format) {
|
||||
return (date == null) ? null : new SimpleDateFormat(format)
|
||||
.format(date);
|
||||
}
|
||||
|
||||
public static final String parseDateToStr(final String format, final Date date) {
|
||||
return new SimpleDateFormat(format).format(date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.yxt.demo.common.utils.date;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2021/11/6 22:52
|
||||
* @Description java 8 日期工具类再封装
|
||||
*/
|
||||
public class LocalDateUtils {
|
||||
|
||||
/**
|
||||
* 比较第一个日期是否小于第二个日期
|
||||
*
|
||||
* @param firstDate 第一个日期
|
||||
* @param secondDate 第二个日期
|
||||
* @return true-小于;false-大于
|
||||
*/
|
||||
public static boolean localDateIsBefore(LocalDate firstDate, LocalDate secondDate) {
|
||||
return firstDate.isBefore(secondDate);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 比较第一个日期是否大于第二个日期
|
||||
*
|
||||
* @param firstDate 第一个日期
|
||||
* @param secondDate 第二个日期
|
||||
* @return true-大于;false-不大于
|
||||
*/
|
||||
public static boolean localDateIsAfter(LocalDate firstDate, LocalDate secondDate) {
|
||||
return firstDate.isAfter(secondDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否相等
|
||||
*
|
||||
* @param firstDate 第一个日期
|
||||
* @param secondDate 第二个日期
|
||||
* @return true-相等;false-不相等
|
||||
*/
|
||||
public static boolean localDateIsEqual(LocalDate firstDate, LocalDate secondDate) {
|
||||
return firstDate.isEqual(secondDate);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 字符串转换datetime
|
||||
*
|
||||
* @param dateTime
|
||||
* @return yyyy-MM-dd HH:mm:ss
|
||||
*/
|
||||
public static Date stringCoverDateTime(String dateTime) {
|
||||
LocalDateTime startDateTime =
|
||||
LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
Date LocalDateTimeToDate = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||
return LocalDateTimeToDate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 字符串转换date
|
||||
*
|
||||
* @param dateTime
|
||||
* @return yyyy-MM-dd
|
||||
*/
|
||||
public static Date stringCoverDate(String dateTime) {
|
||||
LocalDateTime startDateTime =
|
||||
LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
|
||||
Date LocalDateTimeToDate = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||
return LocalDateTimeToDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package com.yxt.demo.common.utils.http;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import okhttp3.*;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2021/11/5 20:57
|
||||
* @Description 封装OkHttp3工具类
|
||||
*/
|
||||
public class OkHttpUtils {
|
||||
|
||||
private static volatile OkHttpClient okHttpClient = null;
|
||||
private static volatile Semaphore semaphore = null;
|
||||
private Map<String, String> headerMap;
|
||||
private Map<String, String> paramMap;
|
||||
private String url;
|
||||
private Request.Builder request;
|
||||
|
||||
/**
|
||||
* 初始化okHttpClient,并且允许https访问
|
||||
*/
|
||||
private OkHttpUtils() {
|
||||
if (okHttpClient == null) {
|
||||
synchronized (OkHttpUtils.class) {
|
||||
if (okHttpClient == null) {
|
||||
TrustManager[] trustManagers = buildTrustManagers();
|
||||
okHttpClient = new OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.writeTimeout(20, TimeUnit.SECONDS)
|
||||
.readTimeout(20, TimeUnit.SECONDS)
|
||||
.sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0])
|
||||
.hostnameVerifier((hostName, session) -> true)
|
||||
.retryOnConnectionFailure(true)
|
||||
.build();
|
||||
addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于异步请求时,控制访问线程数,返回结果
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static Semaphore getSemaphoreInstance() {
|
||||
//只能1个线程同时访问
|
||||
synchronized (OkHttpUtils.class) {
|
||||
if (semaphore == null) {
|
||||
semaphore = new Semaphore(0);
|
||||
}
|
||||
}
|
||||
return semaphore;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建OkHttpUtils
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static OkHttpUtils builder() {
|
||||
return new OkHttpUtils();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加url
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
*/
|
||||
public OkHttpUtils url(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加参数
|
||||
*
|
||||
* @param key 参数名
|
||||
* @param value 参数值
|
||||
* @return
|
||||
*/
|
||||
public OkHttpUtils addParam(String key, String value) {
|
||||
if (paramMap == null) {
|
||||
paramMap = new LinkedHashMap<>(16);
|
||||
}
|
||||
paramMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加请求头
|
||||
*
|
||||
* @param key 参数名
|
||||
* @param value 参数值
|
||||
* @return
|
||||
*/
|
||||
public OkHttpUtils addHeader(String key, String value) {
|
||||
if (headerMap == null) {
|
||||
headerMap = new LinkedHashMap<>(16);
|
||||
}
|
||||
headerMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化get方法
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public OkHttpUtils get() {
|
||||
request = new Request.Builder().get();
|
||||
StringBuilder urlBuilder = new StringBuilder(url);
|
||||
if (paramMap != null) {
|
||||
urlBuilder.append("?");
|
||||
try {
|
||||
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
|
||||
urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
|
||||
append("=").
|
||||
append(URLEncoder.encode(entry.getValue(), "utf-8")).
|
||||
append("&");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
urlBuilder.deleteCharAt(urlBuilder.length() - 1);
|
||||
}
|
||||
request.url(urlBuilder.toString());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化post方法
|
||||
*
|
||||
* @param isJsonPost true等于json的方式提交数据,类似postman里post方法的raw
|
||||
* false等于普通的表单提交
|
||||
* @return
|
||||
*/
|
||||
public OkHttpUtils post(boolean isJsonPost) {
|
||||
RequestBody requestBody;
|
||||
if (isJsonPost) {
|
||||
String json = "";
|
||||
if (paramMap != null) {
|
||||
json = JSON.toJSONString(paramMap);
|
||||
}
|
||||
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
|
||||
} else {
|
||||
FormBody.Builder formBody = new FormBody.Builder();
|
||||
if (paramMap != null) {
|
||||
paramMap.forEach(formBody::add);
|
||||
}
|
||||
requestBody = formBody.build();
|
||||
}
|
||||
request = new Request.Builder().post(requestBody).url(url);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步请求
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String sync() {
|
||||
setHeader(request);
|
||||
try {
|
||||
Response response = okHttpClient.newCall(request.build()).execute();
|
||||
assert response.body() != null;
|
||||
return response.body().string();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return "请求失败:" + e.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步请求,有返回值
|
||||
*/
|
||||
public String async() {
|
||||
StringBuilder buffer = new StringBuilder("");
|
||||
setHeader(request);
|
||||
okHttpClient.newCall(request.build()).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
buffer.append("请求出错:").append(e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
assert response.body() != null;
|
||||
buffer.append(response.body().string());
|
||||
getSemaphoreInstance().release();
|
||||
}
|
||||
});
|
||||
try {
|
||||
getSemaphoreInstance().acquire();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步请求,带有接口回调
|
||||
*
|
||||
* @param callBack
|
||||
*/
|
||||
public void async(ICallBack callBack) {
|
||||
setHeader(request);
|
||||
okHttpClient.newCall(request.build()).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
callBack.onFailure(call, e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
assert response.body() != null;
|
||||
callBack.onSuccessful(call, response.body().string());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 为request添加请求头
|
||||
*
|
||||
* @param request
|
||||
*/
|
||||
private void setHeader(Request.Builder request) {
|
||||
if (headerMap != null) {
|
||||
try {
|
||||
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
|
||||
request.addHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成安全套接字工厂,用于https请求的证书跳过
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
|
||||
SSLSocketFactory ssfFactory = null;
|
||||
try {
|
||||
SSLContext sc = SSLContext.getInstance("SSL");
|
||||
sc.init(null, trustAllCerts, new SecureRandom());
|
||||
ssfFactory = sc.getSocketFactory();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return ssfFactory;
|
||||
}
|
||||
|
||||
private static TrustManager[] buildTrustManagers() {
|
||||
return new TrustManager[]{
|
||||
new X509TrustManager() {
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new X509Certificate[]{};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义一个接口回调
|
||||
*/
|
||||
public interface ICallBack {
|
||||
void onSuccessful(Call call, String data);
|
||||
|
||||
void onFailure(Call call, String errorMsg);
|
||||
}
|
||||
|
||||
/*****************************使用教程************************************************************/
|
||||
|
||||
public static void main(String[] args) {
|
||||
// get请求,方法顺序按照这种方式,切记选择post/get一定要放在倒数第二,同步或者异步倒数第一,才会正确执行
|
||||
OkHttpUtils.builder().url("请求地址,http/https都可以")
|
||||
// 有参数的话添加参数,可多个
|
||||
.addParam("参数名", "参数值")
|
||||
.addParam("参数名", "参数值")
|
||||
// 也可以添加多个
|
||||
.addHeader("Content-Type", "application/json; charset=utf-8")
|
||||
.get()
|
||||
// 可选择是同步请求还是异步请求
|
||||
//.async();
|
||||
.sync();
|
||||
|
||||
// post请求,分为两种,一种是普通表单提交,一种是json提交
|
||||
OkHttpUtils.builder().url("请求地址,http/https都可以")
|
||||
// 有参数的话添加参数,可多个
|
||||
.addParam("参数名", "参数值")
|
||||
.addParam("参数名", "参数值")
|
||||
// 也可以添加多个
|
||||
.addHeader("Content-Type", "application/json; charset=utf-8")
|
||||
// 如果是true的话,会类似于postman中post提交方式的raw,用json的方式提交,不是表单
|
||||
// 如果是false的话传统的表单提交
|
||||
.post(true)
|
||||
.sync();
|
||||
|
||||
// 选择异步有两个方法,一个是带回调接口,一个是直接返回结果
|
||||
OkHttpUtils.builder().url("")
|
||||
.post(false)
|
||||
.async();
|
||||
|
||||
OkHttpUtils.builder().url("").post(false).async(new ICallBack() {
|
||||
@Override
|
||||
public void onSuccessful(Call call, String data) {
|
||||
// 请求成功后的处理
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call call, String errorMsg) {
|
||||
// 请求失败后的处理
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.yxt.demo.common.utils.jwt;
|
||||
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author dimengzhe
|
||||
* @Date 2021/11/6 22:55
|
||||
* @Description
|
||||
*/
|
||||
public class JwtUtils {
|
||||
|
||||
/**
|
||||
* 签名密钥(高度保密)
|
||||
*/
|
||||
private static final String SECRET = "qYYjXt7s1C*nEC%9RCwQGFA$YwPr$Jrj";
|
||||
/**
|
||||
* 签名算法
|
||||
*/
|
||||
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS512;
|
||||
/**
|
||||
* token前缀
|
||||
*/
|
||||
private static final String TOKEN_PREFIX = "Bearer ";
|
||||
/**
|
||||
* 有效期:1天
|
||||
*/
|
||||
private static final Long TIME = 24 * 3600 * 1000L;
|
||||
|
||||
/**
|
||||
* 生成JWT token
|
||||
*
|
||||
* @param map 传入数据
|
||||
* @return
|
||||
*/
|
||||
public static String sign(Map<String, Object> map) {
|
||||
Date now = new Date(System.currentTimeMillis());
|
||||
String jwt = Jwts.builder()
|
||||
// 设置自定义数据
|
||||
.setClaims(map)
|
||||
// 设置签发时间
|
||||
.setIssuedAt(now)
|
||||
// 设置过期时间
|
||||
.setExpiration(new Date(now.getTime() + TIME))
|
||||
.signWith(SIGNATURE_ALGORITHM, SECRET)
|
||||
.compact();
|
||||
return TOKEN_PREFIX + jwt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证JWT token并返回数据。当验证失败时,抛出异常
|
||||
*
|
||||
* @param token token
|
||||
* @return
|
||||
*/
|
||||
public static Map unSign(String token) {
|
||||
try {
|
||||
return Jwts.parser()
|
||||
.setSigningKey(SECRET)
|
||||
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
|
||||
.getBody();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Token验证失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
/* Map<String, Object> map = new HashMap<>();
|
||||
map.put("userName", "admin");
|
||||
map.put("userId", "001");
|
||||
String token = JwtUtils.sign(map, 3600_000);
|
||||
System.out.println(JwtUtils.unSign(token));*/
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("userSid", "123456788");
|
||||
map.put("userName", "你好");
|
||||
// sign(map);
|
||||
// System.out.println(sign(map));
|
||||
Map<String,Object> map1 = unSign("Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyU2lkIjoiMTIzNDU2Nzg4IiwidXNlck5hbWUiOiLkvaDlpb0iLCJleHAiOjE2MzYyOTk0NTgsImlhdCI6MTYzNjIxMzA1OH0.iuyZznSCm0QYneqfck_zc3fpg57YsAdG8k2aLrDY_4NZJwJdVxE7supqLtfEvTC5O0EhG590ShhRsVoU-rbSrA");
|
||||
System.out.println(map1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user