以下都是我工作中用到的工具类,特在此记录:
@Author Jacky Wang
更新记录:
1. 2018年09月06日,第一次更新及补充。
2. 2019年08月06号,新增DateUtils中Java8对于LocalDate及LocalDateTime支持。
05.实用工具类大全
以下都是我工作中用到的工具类,特在此记录:
@Author Jacky Wang
1. ConvertHexUtils工具类
16进制字符串相关类型的转换的工具类。
public class ConvertHexUtils {
/**
* 字符串转换成十六进制字符串
*
* @param String
* str 待转换的ASCII字符串
* @return String 每个Byte之间空格分隔,如: [61 6C 6B]
*/
public static String str2SpaceHexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
sb.append(' ');
}
return sb.toString().trim();
}
/**
* 字符串转换成十六进制字符串
*
* @param String
* str 待转换的ASCII字符串
* @return String 每个Byte之间没有空格分隔,如: [616C6B]
*/
public static String str2NoSpaceHexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString().trim();
}
/**
* 十六进制转换字符串
*
* @param String
* str Byte字符串(Byte之间无分隔符 如:[616C6B])
* @return String 对应的字符串
*/
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
/**
* bytes转换成十六进制字符串
*
* @param byte[]
* b byte数组
* @return String 每个Byte值之间空格分隔
*/
public static String byte2HexStr(byte[] b) {
String stmp = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
sb.append(" ");
}
return sb.toString().toUpperCase().trim();
}
/**
* bytes字符串转换为Byte值
*
* @param String src Byte字符串,每个Byte之间没有分隔符
* @return byte[]
*/
public static byte[] hexStr2Bytes(String src) {
int m = 0, n = 0;
int l = src.length() / 2;
System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
m = i * 2 + 1;
n = m + 1;
ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
}
return ret;
}
/**
* String的字符串转换成unicode的String
*
* @param String strText 全角字符串
* @return String 每个unicode之间无分隔符
* @throws Exception
*/
public static String strToUnicode(String strText) throws Exception {
char c;
StringBuilder str = new StringBuilder();
int intAsc;
String strHex;
for (int i = 0; i < strText.length(); i++) {
c = strText.charAt(i);
intAsc = (int) c;
strHex = Integer.toHexString(intAsc);
if (intAsc > 128)
str.append("\\u" + strHex);
else // 低位在前面补00
str.append("\\u00" + strHex);
}
return str.toString();
}
/**
* unicode的String转换成String的字符串
*
* @param String hex 16进制值字符串 (一个unicode为2byte)
* @return String 全角字符串
*/
public static String unicodeToString(String hex) {
int t = hex.length() / 6;
StringBuilder str = new StringBuilder();
for (int i = 0; i < t; i++) {
String s = hex.substring(i * 6, (i + 1) * 6);
// 高位需要补上00再转
String s1 = s.substring(2, 4) + "00";
// 低位直接转
String s2 = s.substring(4);
// 将16进制的string转为int
int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
// 将int转换为字符
char[] chars = Character.toChars(n);
str.append(new String(chars));
}
return str.toString();
}
}
2. ByteUtils工具类
public class ByteUtils {
/**
* 用来把mac字符串转换为long
*
* @param strMac
* @return
*/
public static long macToLong(String strMac) {
byte[] mb = new BigInteger(strMac, 16).toByteArray();
ByteBuffer mD = ByteBuffer.allocate(mb.length);
mD.put(mb);
long mac = 0;
// 如果长度等于8代表没有补0;
if (mD.array().length == 8) {
mac = mD.getLong(0);
} else if (mD.array().length == 9) {
mac = mD.getLong(1);
}
return mac;
}
public static byte[] getBytes(Object obj) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(obj);
out.flush();
byte[] bytes = bout.toByteArray();
bout.close();
out.close();
return bytes;
}
/**
* 函数名称:hexStr2Byte</br>
* 功能描述:String 转数组
*
* @param hex
* @return 16进制转byte
*/
public static byte[] hexStr2Byte(String hex) {
ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
for (int i = 0; i < hex.length(); i++) {
String hexStr = hex.charAt(i) + "";
i++;
hexStr += hex.charAt(i);
byte b = (byte) Integer.parseInt(hexStr, 16);
bf.put(b);
}
return bf.array();
}
/**
* 函数名称:byteToHex</br>
* 功能描述:byte转16进制
*
* @param b
* @return
*/
public static String byteToHex(byte b) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
return hex.toUpperCase(Locale.getDefault());
}
public static Object getObject(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
Object obj = oi.readObject();
bi.close();
oi.close();
return obj;
}
public static ByteBuffer getByteBuffer(Object obj) throws IOException {
byte[] bytes = ByteUtils.getBytes(obj);
ByteBuffer buff = ByteBuffer.wrap(bytes);
return buff;
}
/**
* byte[] 转short 2字节
*
* @param bytes
* @return
*/
public static short bytesToshort(byte[] bytes) {
return (short) ((bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00));
}
/**
* byte 转Int
*
* @param b
* @return
*/
public static int byteToInt(byte b) {
return (b) & 0xff;
}
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
public static byte[] intToByte(int i) {
byte[] abyte0 = new byte[4];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
return abyte0;
}
public static byte[] LongToByte(Long i) {
byte[] abyte0 = new byte[8];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
abyte0[4] = (byte) ((0xff00000000l & i) >> 32);
abyte0[5] = (byte) ((0xff0000000000l & i) >> 40);
abyte0[6] = (byte) ((0xff000000000000l & i) >> 48);
abyte0[7] = (byte) ((0xff00000000000000l & i) >> 56);
return abyte0;
}
/**
* 函数名称:shortChange</br>
* 功能描述:short 大端转小端
*
* @param mshort
*/
public static short shortChange(Short mshort) {
mshort = (short) ((mshort >> 8 & 0xFF) | (mshort << 8 & 0xFF00));
return mshort;
}
/**
* 函数名称:intChange</br>
* 功能描述:int 大端转小端
*
* @param mint
*/
public static int intChange(int mint) {
mint = (int) (((mint) >> 24 & 0xFF) | ((mint) >> 8 & 0xFF00) | ((mint) << 8 & 0xFF0000)
| ((mint) << 24 & 0xFF000000));
return mint;
}
/**
* 函数名称:intChange</br>
* 功能描述:LONG 大端转小端
*
* @param mint
*/
public static long longChange(long mint) {
mint = (long) (((mint) >> 56 & 0xFF) | ((mint) >> 48 & 0xFF00) | ((mint) >> 24 & 0xFF0000)
| ((mint) >> 8 & 0xFF000000) | ((mint) << 8 & 0xFF00000000l) | ((mint) << 24 & 0xFF0000000000l)
| ((mint) << 40 & 0xFF000000000000l) | ((mint) << 56 & 0xFF00000000000000l));
return mint;
}
/**
* 将byte转换为无符号的short类型
*
* @param b 需要转换的字节数
* @return 转换完成的short
*/
public static short byteToUshort(byte b) {
return (short) (b & 0x00ff);
}
/**
* 将byte转换为无符号的int类型
*
* @param b 需要转换的字节数
* @return 转换完成的int
*/
public static int byteToUint(byte b) {
return b & 0x00ff;
}
/**
* 将byte转换为无符号的long类型
*
* @param b 需要转换的字节数
* @return 转换完成的long
*/
public static long byteToUlong(byte b) {
return b & 0x00ff;
}
/**
* 将short转换为无符号的int类型
*
* @param s 需要转换的short
* @return 转换完成的int
*/
public static int shortToUint(short s) {
return s & 0x00ffff;
}
/**
* 将short转换为无符号的long类型
*
* @param s 需要转换的字节数
* @return 转换完成的long
*/
public static long shortToUlong(short s) {
return s & 0x00ffff;
}
/**
* 将int转换为无符号的long类型
*
* @param i 需要转换的字节数
* @return 转换完成的long
*/
public static long intToUlong(int i) {
return i & 0x00ffffffff;
}
/**
* 将short转换成小端序的byte数组
*
* @param s 需要转换的short
* @return 转换完成的byte数组
*/
public static byte[] shortToLittleEndianByteArray(short s) {
return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).array();
}
/**
* 将int转换成小端序的byte数组
*
* @param i 需要转换的int
* @return 转换完成的byte数组
*/
public static byte[] intToLittleEndianByteArray(int i) {
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(i).array();
}
/**
* 将long转换成小端序的byte数组
*
* @param l
* 需要转换的long
* @return 转换完成的byte数组
*/
public static byte[] longToLittleEndianByteArray(long l) {
return ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(l).array();
}
/**
* 将short转换成大端序的byte数组
*
* @param s
* 需要转换的short
* @return 转换完成的byte数组
*/
public static byte[] shortToBigEndianByteArray(short s) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putShort(s).array();
}
/**
* 将int转换成大端序的byte数组
*
* @param i 需要转换的int
* @return 转换完成的byte数组
*/
public static byte[] intToBigEndianByteArray(int i) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(i).array();
}
/**
* 将long转换成大端序的byte数组
*
* @param l 需要转换的long
* @return 转换完成的byte数组
*/
public static byte[] longToBigEndianByteArray(long l) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putLong(l).array();
}
/**
* 将short转换为16进制字符串
*
* @param s 需要转换的short
* @param isLittleEndian
* 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String shortToHexString(short s, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = shortToLittleEndianByteArray(s);
} else {
byteArray = shortToBigEndianByteArray(s);
}
return byteArrayToHexString(byteArray);
}
/**
* 将int转换为16进制字符串
*
* @param i 需要转换的int
* @param isLittleEndian 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String intToHexString(int i, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = intToLittleEndianByteArray(i);
} else {
byteArray = intToBigEndianByteArray(i);
}
return byteArrayToHexString(byteArray);
}
/**
* 将long转换为16进制字符串
*
* @param l 需要转换的long
* @param isLittleEndian 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String longToHexString(long l, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = longToLittleEndianByteArray(l);
} else {
byteArray = longToBigEndianByteArray(l);
}
return byteArrayToHexString(byteArray);
}
/**
* 将字节数组转换成16进制字符串
*
* @param array 需要转换的字符串
* @param toPrint 是否为了打印输出,如果为true则会每4自己添加一个空格
* @return 转换完成的字符串
*/
public static String byteArrayToHexString(byte[] array, boolean toPrint) {
if (array == null) {
return "null";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append(byteToHex(array[i]));
if (toPrint && (i + 1) % 4 == 0) {
sb.append(" ");
}
}
return sb.toString();
}
/**
* 将字节数组转换成16进制字符串
*
* @param array 需要转换的字符串(字节间没有分隔符)
* @return 转换完成的字符串
*/
public static String byteArrayToHexString(byte[] array) {
return byteArrayToHexString(array, false);
}
/**
* 将字节数组转换成long类型
*
* @param bytes 字节数据
* @return long类型
*/
public static long byteArrayToLong(byte[] bytes) {
return ((((long) bytes[0] & 0xff) << 24) | (((long) bytes[1] & 0xff) << 16) | (((long) bytes[2] & 0xff) << 8)
| (((long) bytes[3] & 0xff) << 0));
}
}
3. RadomUtils随机数工具类:
/**
* @author wangwangjie
*/
public class RandomUtils {
private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUMBERCHAR = "0123456789";
private static final int DATE = 8;
private static final int NANO = 15;
private static final int RANDOM = 9;
/**
* 返回一个定长的随机字符串(只包含大小写字母、数字)
*
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateMixString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateLowerString(int length) {
return generateMixString(length).toLowerCase();
}
/**
* 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateUpperString(int length) {
return generateMixString(length).toUpperCase();
}
/**
* 生成一个定长的纯0字符串
*
* @param length
* 字符串长度
* @return 纯0字符串
*/
public static String generateZeroString(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根据数字生成一个定长的字符串,长度不够前面补0
*
* @param num 数字
* @param fixdlenth 字符串长度
* @return 定长的字符串
*/
public static String toFixdLengthString(long num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!");
}
sb.append(strNum);
return sb.toString();
}
/**
* 每次生成的len位数都不相同
*
* @param param
* @return 定长的数字
*/
public static int getNotSimple(int[] param, int len) {
Random rand = new Random();
for (int i = param.length; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = param[index];
param[index] = param[i - 1];
param[i - 1] = tmp;
}
int result = 0;
for (int i = 0; i < len; i++) {
result = result * 10 + param[i];
}
return result;
}
/**
*
* @Title: getFixStr
* @Description: TODO(获取定长字符串)
* @param: @param str
* @param: @param fixlength
* @param: @return
* @return: String
* @throws
*/
public static String getFixStr(String str, int fixlength) {
if (str.length() > fixlength) {
return str.substring(str.length() - fixlength, str.length());
}
if (str.length() < fixlength) {
int lose = fixlength - str.length();
String randomstr = "";
for (int i = 0; i < lose; i++) {
Double random = Math.random();
randomstr += random.toString().substring(2, 3);
}
return str + randomstr;
}
return str;
}
public static String getDateStr() {
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
return getFixStr(dateFormater.format(date), DATE);
}
/**
*
* @Title: getNanoTimeStr
* @Description: TODO(生成定长的纳秒字符)
* @param: @return
* @return: String
* @throws
*/
public static String getNanoTimeStr(){
String nanostr = System.nanoTime()+"";
return getFixStr(nanostr,NANO);
}
/**
*
* @Title: getRandomStr
* @Description: TODO(获取定长自由数)
* @param: @return
* @return: String
* @throws
*/
public static String getRandomStr(){
String str = "";
Double random = Math.random();
str = random.toString().substring(2, 11);
return getFixStr(str,RANDOM);
}
/**
*
* @Title: generateOrderNo
* @Description: TODO(生成默认32位订单号)
* @param: @return
* @return: String
* @throws
*/
public static String generateOrderNo(){
String res = getDateStr()+getNanoTimeStr()+getRandomStr();
return res;
}
/**
*
* @Title: generateOrderNo
* @Description: TODO(生成带有自定义后缀订单号)
* @param: @param suffix 后缀
* @param: @param counts 少几位
* @param: @return
* @return: String
* @throws
*/
public static String generateOrderNo(String suffix,int counts){
String res = getDateStr()+getNanoTimeStr()+getFixStr(getRandomStr(),RANDOM-counts)+suffix;
return res;
}
public static void main(String[] args) {
/*System.out.println("返回一个定长的随机字符串(只包含大小写字母、数字):" + generateString(10));
System.out.println("返回一个定长的随机纯字母字符串(只包含大小写字母):" + generateMixString(10));
System.out.println("返回一个定长的随机纯小写字母字符串(只包含小写字母):" + generateLowerString(10));
System.out.println("返回一个定长的随机纯大写字母字符串(只包含大写字母):" + generateUpperString(10));
System.out.println("生成一个定长的纯0字符串:" + generateZeroString(10));
System.out.println("根据数字生成一个定长的字符串,长度不够前面补0:" + toFixdLengthString(123, 10));
int[] in = { 1, 2, 3, 4, 5, 6, 7 };
System.out.println("每次生成的len位数都不相同:" + getNotSimple(in, 3));
System.out.println(getDateStr());
System.out.println(getNanoTimeStr());
System.out.println(getRandomStr());
System.out.println(generateOrderNo());
System.out.println(generateOrderNo(".java", 6));*/
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i=0;i<5000000;i++) {
String upperString = generateUpperString(10);
if(!map.containsKey(upperString)) {
map.put(upperString, 1);
} else {
map.put(upperString, map.get(upperString)+1);
}
}
for (Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
if(value > 1) {
System.out.println(key + "---" + value);
}
}
System.err.println(map.keySet().size());
}
}
4. HttpClientUtils工具类
前提:导入httpclient的jar包.
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* @ClassName: HttpClientUtils
* @Description:TODO(HTTPClient工具)
* @author: wwj
* @date: 2018年8月8日 下午7:43:11
*/
@SuppressWarnings("deprecation")
public class HttpClientUtils {
public static final String APPLICATION_JSON = "application/json";
public static final String CONTENT_TYPE_TEXT_JSON = "text/json";
public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
// utf-8字符编码
public static final String CHARSET_UTF_8 = "utf-8";
// HTTP内容类型。
public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
// HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
// 连接管理器
public static PoolingHttpClientConnectionManager pool;
// 请求配置
public static RequestConfig requestConfig;
static {
try {
// System.out.println("初始化HttpClientTest~~~开始");
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
// 配置同时支持 HTTP 和 HTPPS
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
// 初始化连接管理器
pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
pool.setMaxTotal(200);
// 设置最大路由
pool.setDefaultMaxPerRoute(2);
// 根据默认超时限制初始化requestConfig
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
// System.out.println("初始化HttpClientTest~~~结束");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
// 设置请求超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
.setConnectionRequestTimeout(50000).build();
}
public static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
// 设置连接池管理
.setConnectionManager(pool)
// 设置请求配置
.setDefaultRequestConfig(requestConfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build();
return httpClient;
}
/**
* 发送Post请求
*/
public static String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpPost.setConfig(requestConfig);
// Header[] allHeaders = httpPost.getAllHeaders();
// for (Header header : allHeaders) {
// System.out.println(header.getName() + " : " + header.getValue());
// }
// 执行请求
response = httpClient.execute(httpPost);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName() + "-" + header.getValue());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Get请求
*/
public static String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
// System.out.println(header.getName());
// }
// 得到响应类型
// System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送 post请求
*/
public static String sendHttpPost(String httpUrl) {
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
return sendHttpPost(httpPost);
}
/**
* 发送 get请求
*/
public static String sendHttpGet(String httpUrl) {
// 创建get请求
HttpGet httpGet = new HttpGet(httpUrl);
return sendHttpGet(httpGet);
}
/**
* 发送 get请求
*
* @param maps
* 参数
*/
public static String sendHttpGet(String httpUrl, Map<String, String> maps) {
String param = convertStringParamter(maps);
// System.out.println(param);
return sendHttpGet(httpUrl + "?" + param);
}
/**
* 发送 post请求(带文件)
*
* @param httpUrl
* 地址
* @param maps
* 参数
* @param fileLists
* 附件
*/
public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
if (maps != null) {
for (String key : maps.keySet()) {
meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
}
}
if (fileLists != null) {
for (File file : fileLists) {
FileBody fileBody = new FileBody(file);
meBuilder.addPart("files", fileBody);
}
}
HttpEntity reqEntity = meBuilder.build();
httpPost.setEntity(reqEntity);
return sendHttpPost(httpPost);
}
/**
* 发送 post请求,参数(格式:key1=value1&key2=value2)
*/
public static String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (params != null && params.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 post请求
*
* @param maps
* 参数
*/
public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
String parem = convertStringParamter(maps);
return sendHttpPost(httpUrl, parem);
}
/**
* 发送 post请求 发送json数据
*
* @param httpUrl
* @param paramsJson
*/
public static String sendHttpPostJson(String httpUrl, String paramsJson) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
public static String sendHttpPostJson(HttpPost httpPost, String paramsJson) {
try {
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 post请求 发送xml数据
*
* @param httpUrl
* 地址
* @param paramsXml
* 参数(格式 Xml)
*
*/
public static String sendHttpPostXml(String httpUrl, String paramsXml) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (paramsXml != null && paramsXml.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 将map集合的键值对转化成:key1=value1&key2=value2 的形式
*
* @param parameterMap
* 需要转化的键值对集合
* @return 字符串
*/
@SuppressWarnings("rawtypes")
public static String convertStringParamter(Map parameterMap) {
StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if (parameterMap.get(key) != null) {
value = (String) parameterMap.get(key);
} else {
value = "";
}
parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
}
return parameterBuffer.toString();
}
public static String doPost(String url, String json, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
httpPost.setHeader("Accept", APPLICATION_JSON);
// 设置参数
StringEntity se = new StringEntity(json, Charset.forName(charset));
se.setContentType(CONTENT_TYPE_TEXT_JSON);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public static String doBodyPost(String url, Map<String, String> params, String charset, String contentType) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, contentType);
// 设置参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
Object value = null;
for (Entry<String, String> enty : params.entrySet()) {
value = enty.getValue();
if (value instanceof Long) {
formparams.add(new BasicNameValuePair(enty.getKey(), String.valueOf(value)));
} else {
formparams.add(new BasicNameValuePair(enty.getKey(), (String) value));
}
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, charset);
httpPost.setEntity(uefEntity);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
与之配套使用的SSLClient工具类:
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
@SuppressWarnings("deprecation")
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
5. DateUtils日期操作工具类
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @ClassName: DateUtils
* @author: wwj
* @date: 2018年9月6日 下午2:09:57
*/
public class DateUtils {
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String defaultFormatDate(Date date) {
return formatDate(date, DEFAULT_DATE_PATTERN);
}
public static String formatDate(Date date, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(date);
}
public static Date defaultParseDate(String dateStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
return sdf.parse(dateStr);
}
public static Date parseDate(String dateStr, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(dateStr);
}
/**
* Java将Unix时间戳转换成指定格式日期字符串
*
* @param timestampString 时间戳 如:"1473048265";
* @return 返回结果 如:"2016-09-05 16:06:42";
*/
public static String timeStampToDate(String timestampString, String formats) {
if (StringUtils.isEmpty(formats)) {
formats = DEFAULT_DATE_PATTERN;
}
Long timestamp = Long.parseLong(timestampString) * 1000;
String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
return date;
}
/**
* 日期格式字符串转换成时间戳
*/
public static String dateToTimeStamp(String dateStr, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static Long dateToTimeStamp(Date date) {
try {
return date.getTime() / 1000;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 取得指定时间的时间戳(精确到毫秒)
*/
public static String dateToTimeStamp2(Date date) {
try {
return String.valueOf(date.getTime());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 取得当前时间戳(精确到秒)
*/
public static String getNowTimeStamp() {
long time = System.currentTimeMillis();
String nowTimeStamp = String.valueOf(time / 1000);
return nowTimeStamp;
}
public static Date addTimeByType(Date sourceDate, int n, int filed) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(sourceDate);
calendar.add(filed, n);
return calendar.getTime();
}
public static Date addDay(Date souceDate, int day) {
return addTimeByType(souceDate, day, Calendar.DATE);
}
/**
* @Description: 计算指定日期在指定分钟之前或之后的时间
*/
public static Date addMinute(Date sourceDate, int min) {
return addTimeByType(sourceDate, min, Calendar.MINUTE);
}
public static Date addSecond(Date sourceDate, int second) {
return addTimeByType(sourceDate, second, Calendar.SECOND);
}
/**
* @Description: 判断指定时间是否在时间段内
*/
public static boolean belongCalendar(Date sourceDate, Date beginDate, Date endDate) {
Calendar source = Calendar.getInstance();
source.setTime(sourceDate);
Calendar begin = Calendar.getInstance();
begin.setTime(beginDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
return (source.after(begin) && source.before(end)) ? true : false;
}
/**----------------------------------------------------------------------------------*/
/**
* Date转LocalDate
*
* @param date
* @return
*/
public static LocalDate date2LocalDate(Date date) {
if (null == date) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* LocalDate转Date
*
* @param localDate
* @return
*/
public static Date localDate2Date(LocalDate localDate) {
if (null == localDate) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
/**
* date2LocalDateTime
*
* @param date
* @return
*/
public static LocalDateTime date2LocalDateTime(Date date) {
if (null == date) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* localDateTime转Date
*
* @param localDateTime
* @return
*/
public static Date localDateTime2Date(LocalDateTime localDateTime) {
if (null == localDateTime) {
return null;
}
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
/**
* 获取指定时间是当年的第几周
* 自然周标准:以ISO8061 为准
* 一年的第一个自然周应当满足:
* 1. 有第一个星期四
* 2. 包含1月4号
* 3. 第一个自然周应当有4个或者4个以上的天数
* 4. 这个星期开始的时间(即周一)在去年的12月29号(星期一)到今年的1月4号之间
*/
public static int getNumOfWeekInCurrentYear(Date date) {
WeekFields weekFields = WeekFields.ISO;
LocalDate localDate = date2LocalDate(date);
return localDate.get(weekFields.weekOfWeekBasedYear());
}
/**
* 根据给定的某一年某一周获取该周的日期范围
*
* @param week Domain: 1 to 53.
* @param year
* @return
*/
public static Interval getDateIntervalByWeekNumber(int week, int year) {
// Build a String in ISO 8601 Week format: YYYY-Www-D
String input = (String.format("%04d", year) + "-W" + String.format("%02d", week) + "-1");
// Specify the time zone by which to define the beginning of a day.
DateTimeZone timeZone = DateTimeZone.UTC; // Or: DateTimeZone.forID( "America/Montreal" );
// Calculate beginning and ending, using Half-Open (inclusive, exclusive) approach.
DateTime dateTimeStart = new DateTime(input, timeZone);
DateTime dateTimeStop = dateTimeStart.plusWeeks(1);
// Use Joda-Time's tidy Interval class to represent the entire week. Use getters to access start and stop.
Interval weekInterval = new Interval(dateTimeStart, dateTimeStop);
return weekInterval;
}
/**
* 获取给定月份第一天的时间
*
* @param month
* @param year
* @return
*/
public static Date getFirstDayOfMonth(int month, int year) throws ParseException {
LocalDate initial = LocalDate.of(year, month, 1);
LocalDate start = initial.withDayOfMonth(1);
return localDate2Date(start);
}
/**
* 获取给定月份最后一天的时间
*
* @param month
* @param year
* @return
*/
public static Date getLastDayOfMonth(int month, int year) throws ParseException {
LocalDate initial = LocalDate.of(year, month, 1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());
// 格式化日期
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String endDayOfMonth = end.format(dateTimeFormatter) + " 23:59:59";
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
return sdf.parse(endDayOfMonth);
}
}
7. BeanUtils工具类
public class BeanUtil {
/**
* 将Map集合转换成一个Object对象
* @param map
* @param beanClass
* @return
* @throws Exception
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
/**
* 将对象的属性转储为Map<String,Object>
* @param obj
* @return
* @throws Exception
*/
public static Map<String, Object> objectToMap(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
/**
* 将对象的属性转为Map<String, String>
* @param obj
* @return
* @throws Exception
*/
public static Map<String, String> objectToMapStr(Object obj) throws Exception {
if (obj == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
Object value = null;
String vstr = "";
for (Field field : declaredFields) {
field.setAccessible(true);
value = field.get(obj);
if (value != null) {
vstr = String.valueOf(value);
} else {
vstr = "";
}
map.put(field.getName(), vstr);
}
return map;
}
}
8. FastJsonUtils工具类
前提条件:引入阿里巴巴fastjson的maven包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
/**
* @ClassName: FastJsonUtils
* @author: wwj
* @date: 2018年9月6日 下午2:12:59
*/
@SuppressWarnings("unchecked")
public class FastJsonUtils {
private static final SerializeConfig CONFIG;
static {
CONFIG = new SerializeConfig();
CONFIG.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
CONFIG.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] FEATURES = { SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteDateUseDateFormat // 日期格式化,默认为yyyy-MM-dd HH:mm:ss
//SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
//SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而不是null
//SerializerFeature.PrettyFormat // 是否需要格式化输出Json数据
};
/**
* Author:Jack Time:2017年9月2日下午4:24:14
*
* @param object
* @return Return:String Description:将对象转成成Json对象
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object, CONFIG, FEATURES);
}
/**
* @Title: toJSONStringWithDateFormat
* @Description: TODO(使用指定的日期格式将对象转成json字符串)
* @param: @param object
* @param: @return
* @return: String
* @throws
*/
public static String toJSONStringWithDateFormat(Object object) {
return JSON.toJSONStringWithDateFormat(object, ForeverConst.CommonStatus.DEFAULT_DATE_PATTERN, FEATURES);
}
/**
* Author:Jack Time:2017年9月2日下午4:27:25
*
* @param object
* @return Return:String Description:使用和json-lib兼容的日期输出格式
*/
public static String toJSONNoFeatures(Object object) {
return JSON.toJSONString(object, CONFIG);
}
/**
* Author:Jack Time:2017年9月2日下午4:24:54
*
* @param jsonStr
* @return Return:Object Description:将Json数据转换成JSONObject
*/
public static JSONObject toJsonObj(String jsonStr) {
return (JSONObject) JSON.parse(jsonStr);
}
/**
* 将javabean转化为序列化的JSONObject对象
* @param keyvalue
* @return
*/
public static JSONObject beanToJsonObj(Object bean) {
String jsonStr = JSON.toJSONString(bean);
JSONObject objectJson = (JSONObject) JSON.parse(jsonStr);
return objectJson;
}
/**
* Author:Jack Time:2017年9月2日下午4:25:20
* @param jsonStr
* @param clazz
* @return Return:T Description:将Json数据转换成Object
*/
public static <T> T toBean(String jsonStr, Class<T> clazz) {
return JSON.parseObject(jsonStr, clazz);
}
/**
* Author:Jack Time:2017年9月2日下午4:25:34
* @param jsonStr
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static <T> Object[] toArray(String jsonStr) {
return toArray(jsonStr, null);
}
/**
* Author:Jack Time:2017年9月2日下午4:25:57
*
* @param jsonStr
* @param clazz
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static <T> Object[] toArray(String jsonStr, Class<T> clazz) {
return JSON.parseArray(jsonStr, clazz).toArray();
}
/**
* Author:Jack Time:2017年9月2日下午4:26:08
*
* @param jsonStr
* @param clazz
* @return Return:List<T> Description:将Json数据转换为List
*/
public static <T> List<T> toList(String jsonStr, Class<T> clazz) {
return JSON.parseArray(jsonStr, clazz);
}
/**
* json字符串转化为map
* @param s
* @return
*/
public static <K, V> Map<K, V> stringToCollect(String s) {
Map<K, V> m = ((Map<K, V>) JSONObject.parseObject(s));
return m;
}
/**
* 将map转化为string
* @param m
* @return
*/
public static <K, V> String collectToString(Map<K, V> m) {
String s = JSONObject.toJSONString(m);
return s;
}
/**
* Author:Jack Time:2017年9月2日下午4:19:00
*
* @param t
* @param file
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static <T> void writeJsonToFile(T t, File file) throws IOException {
String jsonStr = JSONObject.toJSONString(t, SerializerFeature.PrettyFormat);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(jsonStr);
bw.close();
}
/**
* Author:Jack Time:2017年9月2日下午4:19:12
*
* @param t
* @param filename
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static <T> void writeJsonToFile(T t, String filename) throws IOException {
writeJsonToFile(t, new File(filename));
}
/**
* Author:Jack Time:2017年9月2日下午4:22:07
*
* @param cls
* @param file
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static <T> T readJsonFromFile(Class<T> cls, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), cls);
}
/**
* Author:Jack Time:2017年9月2日下午4:22:30
*
* @param cls
* @param filename
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static <T> T readJsonFromFile(Class<T> cls, String filename) throws IOException {
return readJsonFromFile(cls, new File(filename));
}
/**
* Author:Jack Time:2017年9月2日下午4:23:06
*
* @param typeReference
* @param file
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static <T> T readJsonFromFile(TypeReference<T> typeReference, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), typeReference);
}
/**
* Author:Jack Time:2017年9月2日下午4:23:11
*
* @param typeReference
* @param filename
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static <T> T readJsonFromFile(TypeReference<T> typeReference, String filename) throws IOException {
return readJsonFromFile(typeReference, new File(filename));
}
}
9、RequestUtils工具类
/**
* 解析HttpServletRequest参数
*/
public class RequestUtils {
/**
* 获取所有request请求参数key-value
*
* @param request
* @return
*/
public static Map<String, String> getRequestParams(HttpServletRequest request){
Map<String, String> params = new HashMap<String, String>();
if(null != request){
Set<String> paramsKey = request.getParameterMap().keySet();
for(String key : paramsKey){
params.put(key, request.getParameter(key));
}
}
return params;
}
/**
*
* @Title: getRequestPostStr
* @Description: TODO(获取post请求字符)
* @param: @param request
* @param: @return
* @param: @throws IOException
* @return: String
* @throws
*/
public static String getRequestPostStr(HttpServletRequest request)throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
/**
*
* @Title: getRequestPostBytes
* @Description: TODO(获取请求体字节)
* @param: @param request
* @param: @return
* @param: @throws IOException
* @return: byte[]
* @throws
*/
public static byte[] getRequestPostBytes(HttpServletRequest request)throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
/**
* @Title: getRequestBodyByReader
* @Description: TODO(获取微信回调函数参数,返回xml)
* @param: @param request
* @param: @return
* @param: @throws IOException
* @return: String
* @throws
*/
public static String getRequestBodyByReader(HttpServletRequest request) throws IOException {
String tempLine;
String result = "";
try {
if(request != null) {
while ((tempLine = request.getReader().readLine()) != null) {
result += tempLine;
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
if(request.getReader() != null) {
request.getReader().close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
10. FileHashUtil计算文件大小的哈希值工具类
/**
- @ClassName: FileHashUtil
- @Description:TODO(计算文件大小的哈希值)
- @author: wangwangjie
- @date: 2017年11月2日 下午4:35:09
*/
public class FileHashUtil {
public static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static final String hashType = "MD5";/**
* @Title: MD5File
* @Description: TODO(根据文件名计算文件哈希值)
* @param: @param fileName
* @param: @return
* @param: @throws Exception
* @return: String
* @throws
*/
public static String MD5File(String fileName)
throws Exception {
// String fileName = args[0];
System.out.println("需要获取hash的文件为: " + fileName);
MessageDigest md = MessageDigest.getInstance(hashType);
InputStream fis = null;
try {
fis = new FileInputStream(fileName);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
md.update(buffer, 0, numRead);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (fis != null) {
fis.close();
}
}
return toHexString(md.digest());
}
/**
* @Title: MD5Stream
* @Description: TODO(根据字节流数组计算文件哈希值)
* @param: @param input
* @param: @return
* @param: @throws NoSuchAlgorithmException
* @return: String
* @throws
*/
public static String MD5Stream(byte[] input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(hashType);
md.update(input);
//System.out.println("字节流的哈希值 >>>" + toHexString(input));
return toHexString(md.digest());
}
public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++ ) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] fileNames = new String[]{"E:/study/project/license-client-jar/target/license-client-jar-with-dependencies.jar"};
for (String fileName : fileNames) {
String md5File = FileHashUtil.MD5File(fileName);
System.out.println(md5File);
}
}
}
11. RedisClient工具类
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
@Component
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RedisClient {
@Autowired
private RedisTemplate redisTemplate;
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
*
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合获取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
12. JedisClusterUtils集群工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.invengo.common.utils.FastJsonUtils;
import cn.invengo.middleware.model.property.RedisProperty;
import redis.clients.jedis.JedisCluster;
/**
* @ClassName: JedisClusterClient
* @Description:TODO(redis集群的基础操作工具)
* @author: wwj
* @date: 2018年8月27日 下午3:15:22
*/
@Component
public class JedisClusterClient {
@Autowired
private JedisCluster jedisCluster;
@Autowired
private RedisProperty redisProperty;
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
if (value instanceof String) {
jedisCluster.set(key, value.toString());
} else {
jedisCluster.set(key, FastJsonUtils.toJSONStringWithDateFormat(value));
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
if (value instanceof String) {
jedisCluster.setex(key, Integer.valueOf(expireTime + ""), value.toString());
} else {
jedisCluster.setex(key, Integer.valueOf(expireTime + ""), FastJsonUtils.toJSONStringWithDateFormat(value));
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 设置缓存,并且由配置文件指定过期时间
*
* @param key
* @param value
*/
public void setWithExpireTime(String key, String value) {
try {
int expireSeconds = redisProperty.getTimeout();
set(key, value, Long.valueOf(expireSeconds));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
return jedisCluster.get(key);
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return jedisCluster.exists(key);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
jedisCluster.del(key);
}
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
}
13. EncryptUtils加密算法工具类
package cn.invengo.middleware.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
public class EncryptUtil {
public static final String MD5="MD5";
public static final String UTF8="UTF-8";
/**
* 采用加密算法加密字符串数据 转成长度为32的字符串
* @param str
* @param algorithm 采用的加密算法
* @param charset 指定转化之后的字符串编码
* @return
*/
public static String encryptionStr32(String str, String algorithm,String charset) {
// 加密之后所得字节数组
byte[] bytes = encryptionStrBytes(str,algorithm,charset);
return bytesConvertToHexString(bytes);
}
/**
* 采用加密算法加密字符串数据 转成长度为32的字符串
* @param str 需要加密的数据
* @param algorithm 采用的加密算法
* @return 字节数据
*/
public static String encryptionStr32(String str, String algorithm) {
return encryptionStr32(str,algorithm,"");
}
public static String encryptPassword(String password) {
return encryptionStr32(password, MD5, UTF8);
}
/**
* 采用加密算法加密字符串数据 转成长度为16的字符串
* @param str
* @param algorithm 采用的加密算法
* @param charset 指定转化之后的字符串编码
* @return
*/
public static String encryptionStr16(String str, String algorithm,String charset) {
return encryptionStr32(str,algorithm,charset).substring(8,24);
}
/**
* 采用加密算法加密字符串数据 转成长度为16的字符串
* @param str 需要加密的数据
* @param algorithm 采用的加密算法
* @return 字节数据
*/
public static String encryptionStr16(String str, String algorithm) {
return encryptionStr32(str,algorithm,"").substring(8,24);
}
/**
* 采用加密算法加密字符串数据
* @param str 需要加密的数据
* @param algorithm 采用的加密算法
* @param charset 指定转化之后的字符串编码
* @return 字节数据
*/
public static byte[] encryptionStrBytes(String str, String algorithm, String charset) {
// 加密之后所得字节数组
byte[] bytes = null;
try {
// 获取MD5算法实例 得到一个md5的消息摘要
MessageDigest md = MessageDigest.getInstance(algorithm);
//添加要进行计算摘要的信息
if(null==charset||"".equals(charset)) {
md.update(str.getBytes());
}else{
md.update(str.getBytes(charset));
}
//得到该摘要
bytes = md.digest();
} catch (NoSuchAlgorithmException e) {
System.out.println("加密算法: "+ algorithm +" 不存在: ");
} catch (UnsupportedEncodingException e) {
System.out.println("数据加密指定的编码格式不支持: " + charset);
}
return null==bytes?null:bytes;
}
/**
* 把字节数组转化成字符串返回
* @param bytes
* @return
*/
public static String bytesConvertToHexString(byte [] bytes) {
StringBuffer sb = new StringBuffer();
for (byte aByte : bytes) {
String s=Integer.toHexString(0xff & aByte);
if(s.length()==1){
sb.append("0"+s);
}else{
sb.append(s);
}
}
return sb.toString();
}
public final static String md5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String signRequest(Map<String, String> params,String secret,String rmkey) {
// 从参数中移除签名本身
if (params.containsKey(rmkey)) {
params.remove(rmkey);
}
String[] keys = params.keySet().toArray(new String[0]);
Arrays.sort(keys);
StringBuilder query = new StringBuilder();
query.append(secret);
for (String key : keys) {
Object value = params.get(key);
if (!key.isEmpty() && value != null) {
query.append(key).append(value.toString());
}
}
query.append(secret);
String md5 = encryptionStr32(query.toString(),MD5,UTF8);
return md5.toUpperCase();
}
public static String signRequest(Map<String, String> params,String rmkey) {
// 从参数中移除签名本身
if (params.containsKey(rmkey)) {
params.remove(rmkey);
}
String[] keys = params.keySet().toArray(new String[0]);
Arrays.sort(keys);
StringBuilder query = new StringBuilder();
for (String key : keys) {
Object value = params.get(key);
if (!key.isEmpty() && value != null) {
query.append(key).append(value.toString());
}
}
String md5 = encryptionStr32(query.toString(),MD5,UTF8);
return md5.toUpperCase();
}
/**
* 生成 uuid,最长32位,如length不合法默认32位
* @return
*/
public static String generateUUID(int length) {
if (length <= 0 || length > 32) {
length = 32;
}
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, length);
}
}











网友评论