Spring boot常用工具集
- 请求相关(GET、POST、PUT、DELETE)
- 类对象和Map转换
- Json转Map
- 字符串相关
-
请求相关(GET、POST、PUT、DELETE)
package com.hry.myapp.utils;
import org.apache.http.HttpResponse;
import org.apache.http.NamevaluePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNamevaluePair;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
public static HttpResponse doGet(String host, String path, String method,
Map headers,
Map querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map headers,
Map querys,
Map bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List namevaluePairList = new ArrayList();
for (String key : bodys.keySet()) {
namevaluePairList.add(new BasicNamevaluePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(namevaluePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map headers,
Map querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map headers,
Map querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doDelete(String host, String path, String method,
Map headers,
Map querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (StringUtils.isNotBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
类对象和Map转换
package com.hry.myapp.utils;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.alibaba.druid.sql.ast.SQLStructDataType.Field;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
public class CommonUtils {
@SuppressWarnings("deprecation")
public static T mapToObject(Map map, Class clazz) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+00:00");
Set set = map.keySet();
if (map == null) {
return null;
}
T obj = null;
try {
// 使用newInstance来创建对象
obj = clazz.newInstance();
// 获取类中的所有字段
java.lang.reflect.Field[] fields = obj.getClass().getDeclaredFields();
for (java.lang.reflect.Field field : fields) {
int mod = field.getModifiers();
// 判断是拥有某个修饰符
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
// 当字段使用private修饰时,需要加上
field.setAccessible(true);
// 获取参数类型名字
String filedTypeName = field.getType().getName();
// 判断是否为时间类型,使用equalsIgnoreCase比较字符串,不区分大小写
// 给obj的属性赋值
if(set.contains(field.getName())){
if(filedTypeName.equals("int")) {
int value = Integer.parseInt(map.get(field.getName()).toString()) ;
field.set(obj, value);
}else if(filedTypeName.equals("float")) {
float value = Float.parseFloat(map.get(field.getName()).toString()) ;
field.set(obj, value);
}else if(filedTypeName.equalsIgnoreCase("java.util.date")){
String datetimestamp = map.get(field.getName()).toString();
if (datetimestamp.equalsIgnoreCase("null")) {
field.set(obj, null);
} else {
Long value = Long.parseLong(map.get(field.getName()).toString()) ;
Date d = new Date(value) ;
field.set(obj, d);
}
}else {
field.set(obj, map.get(field.getName()));
}
//
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
@SuppressWarnings("deprecation")
public static Map ObjectToMap(Object obj) {
Map propertiesMap=new HashMap<>();
java.lang.reflect.Field[] fields = obj.getClass().getDeclaredFields();
for(int i = 0 , len = fields.length; i < len; i++) {
// 对于每个属性,获取属性名
String varName = fields[i].getName();
try {
// 获取原来的访问控制权限
boolean accessFlag = fields[i].isAccessible();
// 修改访问控制权限
fields[i].setAccessible(true);
// 获取在对象f中属性fields[i]对应的对象中的变量
Object o;
try {
o = fields[i].get(obj);
propertiesMap.put(varName,o);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 恢复访问控制权限
fields[i].setAccessible(accessFlag);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
return propertiesMap;
}
}
Json转Map
package com.hry.myapp.utils;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
public Map jsonToMap(String json) throws JsonMappingException, JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
Map resultMap = mapper.readValue(json, new TypeReference>(){});
return resultMap;
}
}
字符串相关
字符串空与非空判断
package com.hry.myapp.utils;
public class StringUtils {
public static boolean isNotBlank(String str) {
return (str==null&&"".equals(str))? true:false ;
}
public static boolean isBlank(String str) {
return "".equals(str) ;
}
}