Java常用工具类
为了方便以后工作中进行查找
时间工具类
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public final static String MOTH_PATTERN = "MM";
public final static String YEAR_PATTERN = "yyyy";
public final static String DATE_PATTERN = "yyyy-MM-dd";
public static final String DATETIME_PATTERN = "yyyy/MM/dd";
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
public static String format(Date date, String pattern) {
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
public static Date stringToDate(String strDate, String pattern) {
if (StringUtils.isBlank(strDate)) {
return null;
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return fmt.parseLocalDateTime(strDate).toDate();
}
public static Date[] getWeekStartAndEnd(int week) {
DateTime dateTime = new DateTime();
LocalDate date = new LocalDate(dateTime.plusWeeks(week));
date = date.dayOfWeek().withMinimumValue();
Date beginDate = date.toDate();
Date endDate = date.plusDays(6).toDate();
return new Date[]{beginDate, endDate};
}
public static Date addDateSeconds(Date date, int seconds) {
DateTime dateTime = new DateTime(date);
return dateTime.plusSeconds(seconds).toDate();
}
public static Date addDateMinutes(Date date, int minutes) {
DateTime dateTime = new DateTime(date);
return dateTime.plusMinutes(minutes).toDate();
}
public static Date addDateHours(Date date, int hours) {
DateTime dateTime = new DateTime(date);
return dateTime.plusHours(hours).toDate();
}
public static Date addDateDays(Date date, int days) {
DateTime dateTime = new DateTime(date);
return dateTime.plusDays(days).toDate();
}
public static Date addDateWeeks(Date date, int weeks) {
DateTime dateTime = new DateTime(date);
return dateTime.plusWeeks(weeks).toDate();
}
public static Date addDateMonths(Date date, int months) {
DateTime dateTime = new DateTime(date);
return dateTime.plusMonths(months).toDate();
}
public static Date addDateYears(Date date, int years) {
DateTime dateTime = new DateTime(date);
return dateTime.plusYears(years).toDate();
}
public static int dayDvalue(Date startDate, Date endDate) {
startDate = stringToDate(format(startDate), DATE_PATTERN);
Long startTime = startDate.getTime();
endDate = stringToDate(format(endDate), DATE_PATTERN);
Long endTime = endDate.getTime();
return (int) ((endTime - startTime) / (1000L * 3600L * 24L));
}
public static int monthDvalue(Date startDate, Date endDate) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DateUtils.DATE_PATTERN);
DateTime start = formatter.parseDateTime(DateUtils.format(startDate, DateUtils.DATE_PATTERN));
DateTime end = formatter.parseDateTime(DateUtils.format(endDate, DateUtils.DATE_PATTERN));
int rt = Months.monthsBetween(start, end).getMonths();
return rt;
}
public static Date getMonthFirstDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
public static Date getFirstDayOfMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month - 1);
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, firstDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String firstDayOfMonth = sdf.format(cal.getTime()) + " 00:00:00";
return stringToDate(firstDayOfMonth, "yyyy-MM-dd HH:mm:ss");
}
public static Date getLastDayOfMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month - 1);
int lastDay = 0;
if (month == 2) {
lastDay = cal.getLeastMaximum(Calendar.DAY_OF_MONTH);
} else {
lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
cal.set(Calendar.DAY_OF_MONTH, lastDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String lastDayOfMonth = sdf.format(cal.getTime()) + " 23:59:59";
return stringToDate(lastDayOfMonth, "yyyy-MM-dd HH:mm:ss");
}
public static Date getLastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendar.getTime();
}
public static Integer getMonth(Date date) {
return Integer.valueOf(format(date, "MM"));
}
public static Integer getYear(Date date) {
return Integer.valueOf(format(date, "yyyy"));
}
pojo工具类
import com.mit.common.exception.BeanConstructException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BeanUtils {
public static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);
public BeanUtils() {
}
public static <T, V> V toBean(T t, Class<V> c) throws BeanConstructException {
if (t != null && c != null) {
try {
return JsonUtils.json2object(JsonUtils.object2json(t), c);
} catch (Exception var3) {
logger.error(var3.getMessage());
var3.printStackTrace();
throw new BeanConstructException("Bean 转化异常,请生成 " + c.getName() + "的构造方法!");
}
} else {
return null;
}
}
public static <T, V> List<V> toList(List<T> t, Class<V> c) throws BeanConstructException {
if (t != null && c != null) {
try {
return JsonUtils.json2list(JsonUtils.list2json(t), c);
} catch (Exception var3) {
logger.error(var3.getMessage());
var3.printStackTrace();
throw new BeanConstructException("Bean 转化异常,请生成 " + c.getName() + "的构造方法!");
}
} else {
return null;
}
}
public static Object getField(Object target, String fieldName) {
return getField(target, findField(target.getClass(), fieldName));
}
public static Object getField(Object target, Field field) {
try {
boolean accessible = field.isAccessible();
field.setAccessible(true);
Object result = field.get(target);
field.setAccessible(accessible);
return result;
} catch (Exception var4) {
throw new IllegalStateException("获取对象的属性[" + field.getName() + "]值失败", var4);
}
}
public static Field findField(Class<?> targetClass, String fieldName) {
Iterator iterator = getAllDeclaredField(targetClass).iterator();
while(iterator.hasNext()) {
Field field = (Field)iterator.next();
if (fieldName.equals(field.getName())) {
return field;
}
}
return null;
}
public static List<Field> getAllDeclaredField(Class<?> targetClass, String... excludeFieldNames) {
List<Field> fields = new ArrayList();
Field[] declaredFields = targetClass.getDeclaredFields();
int len = declaredFields.length;
for(int i = 0; i < len; ++i) {
Field field = declaredFields[i];
if (!CollectionUtils.contains(excludeFieldNames, field.getName())) {
fields.add(field);
}
}
Class<?> parentClass = targetClass.getSuperclass();
if (parentClass != Object.class) {
fields.addAll(getAllDeclaredField(parentClass, excludeFieldNames));
}
return fields;
}
public static void copy(Object source, Object target) {
org.springframework.beans.BeanUtils.copyProperties(source, target);
}
public static <T, V> V copy(T t, Class<V> c) throws BeanConstructException {
if (t != null && c != null) {
try {
V v = c.newInstance();
org.springframework.beans.BeanUtils.copyProperties(t, v);
return v;
} catch (Exception var3) {
logger.error(var3.getMessage());
var3.printStackTrace();
throw new BeanConstructException("Bean 转化异常,请生成 " + c.getName() + "的构造方法!");
}
} else {
return null;
}
}
}
JSON工具类
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ValueOperations<String, String> valueOperations;
@Autowired
private HashOperations<String, String, Object> hashOperations;
@Autowired
private ListOperations<String, Object> listOperations;
@Autowired
private SetOperations<String, Object> setOperations;
@Autowired
private ZSetOperations<String, Object> zSetOperations;
public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
public final static long NOT_EXPIRE = -1;
public Long increment(String key) {
return valueOperations.increment(key);
}
public void set(String key, Object value, long expire) {
valueOperations.set(key, toJson(value));
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
}
public void set(String key, Object value) {
set(key, value, DEFAULT_EXPIRE);
}
public <T> T get(String key, Class<T> clazz, long expire) {
String value = valueOperations.get(key);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value == null ? null : fromJson(value, clazz);
}
public void expire(String key,Long expire){
expire(key,expire,TimeUnit.SECONDS);
}
public void expire(String key,Long expire,TimeUnit timeUnit){
redisTemplate.expire(key, expire, timeUnit);
}
public <T> T get(String key, Class<T> clazz) {
return get(key, clazz, NOT_EXPIRE);
}
public String get(String key, long expire) {
String value = valueOperations.get(key);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value;
}
public String get(String key) {
return get(key, NOT_EXPIRE);
}
public void delete(String key) {
redisTemplate.delete(key);
}
private String toJson(Object object) {
if (object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String) {
return String.valueOf(object);
}
return JSON.toJSONString(object);
}
private <T> T fromJson(String json, Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
}
金额转换工具类
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseYuanUtil {
private static final Pattern AMOUNT_PATTERN = Pattern.compile("^(0|[1-9]\\d{0,11})\\.(\\d\\d)$");
private static final char[] RMB_NUMS = "零壹贰叁肆伍陆柒捌玖".toCharArray();
private static final String[] UNITS = {"元", "角", "分", "整"};
private static final String[] U1 = {"", "拾", "佰", "仟"};
private static final String[] U2 = {"", "万", "亿"};
public static String convert(String amount) throws IllegalArgumentException {
amount = amount.replace(",", "");
if (amount.equals("0.00")) {
throw new IllegalArgumentException("金额不能为零.");
}
Matcher matcher = AMOUNT_PATTERN.matcher(amount);
if (!matcher.find()) {
throw new IllegalArgumentException("输入金额有误.");
}
String integer = matcher.group(1);
String fraction = matcher.group(2);
String result = "";
if (!integer.equals("0")) {
result += integer2rmb(integer) + UNITS[0];
}
if (fraction.equals("00")) {
result += UNITS[3];
} else if (fraction.startsWith("0") && integer.equals("0")) {
result += fraction2rmb(fraction).substring(1);
} else {
result += fraction2rmb(fraction);
}
return result;
}
private static String fraction2rmb(String fraction) {
char jiao = fraction.charAt(0);
char fen = fraction.charAt(1);
return (RMB_NUMS[jiao - '0'] + (jiao > '0' ? UNITS[1] : ""))
+ (fen > '0' ? RMB_NUMS[fen - '0'] + UNITS[2] : "");
}
private static String integer2rmb(String integer) {
StringBuilder buffer = new StringBuilder();
int i, j;
for (i = integer.length() - 1, j = 0; i >= 0; i--, j++) {
char n = integer.charAt(i);
if (n == '0') {
if (i < integer.length() - 1 && integer.charAt(i + 1) != '0') {
buffer.append(RMB_NUMS[0]);
}
if (j % 4 == 0) {
if (i > 0 && integer.charAt(i - 1) != '0' || i > 1 && integer.charAt(i - 2) != '0'
|| i > 2 && integer.charAt(i - 3) != '0') {
buffer.append(U2[j / 4]);
}
}
} else {
if (j % 4 == 0) {
buffer.append(U2[j / 4]);
}
buffer.append(U1[j % 4]);
buffer.append(RMB_NUMS[n - '0']);
}
}
return buffer.reverse().toString();
}
}
微信工具类
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
public class WeixinUtils {
@Value("${weixin.mp.appid:}")
private String appid;
@Value("${weixin.mp.mchid:}")
private String mchid;
@Value("${weixin.mp.appSecret:}")
private String appSecret;
@Value("${projectUrl:}")
private String projectUrl;
@Resource
RedisUtils redisUtils;
@Resource
WxPayUtils wxPayUtils;
public String authGetAccessToken() {
String access_token = null;
try {
access_token = redisUtils.get(Constant.WX_MP_ACCESS_TOKEN_KEY);
if (!Strings.isNullOrEmpty(access_token)) {
return access_token;
}
ResponseEntity responseEntity = RestTemplateUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid +
"&secret=" + appSecret, String.class);
log.info("获取小程序的access_token:{}", responseEntity.getBody().toString());
JSONObject jsonObject = JsonUtils.string2jsonObject(responseEntity.getBody().toString());
access_token = jsonObject.getString("access_token");
long expires_in = jsonObject.getLongValue("expires_in");
if (!Strings.isNullOrEmpty(access_token)) {
redisUtils.set(Constant.WX_MP_ACCESS_TOKEN_KEY, access_token, expires_in);
}
} catch (Exception e) {
log.error("获取小程序的access_token:{}", e);
}
return access_token;
}
public JSONObject authCode2Session(String js_code) {
if (Strings.isNullOrEmpty(js_code)) {
return null;
}
try {
Map<String, String> map = new HashMap();
map.put("APPID", appid);
map.put("SECRET", appSecret);
map.put("JSCODE", js_code);
ResponseEntity responseEntity = RestTemplateUtils.get("https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&" +
"js_code={JSCODE}&grant_type=authorization_code", String.class, map);
log.info("获取小程序openid:{}", responseEntity.getBody().toString());
return JsonUtils.string2jsonObject(responseEntity.getBody().toString());
} catch (Exception e) {
log.error("获取小程序openid:{}", e);
return null;
}
}
public void uniformMessageSend(String touser, JSONObject weapp_template_msg, JSONObject mp_template_msg) {
try {
Map<String, Object> map = new HashMap();
String access_token = this.authGetAccessToken();
map.put("access_token", access_token);
map.put("touser", touser);
map.put("weapp_template_msg", weapp_template_msg);
map.put("mp_template_msg", mp_template_msg);
ResponseEntity responseEntity = RestTemplateUtils.post("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + access_token
, JsonUtils.map2json(map), String.class);
log.info("小程序发送统一服务消息:请求:{}响应:{}", JsonUtils.map2json(map), responseEntity.getBody().toString());
} catch (Exception e) {
log.error("{}", e);
}
}
public void subscribeMessageSend(String touser, String template_id, String page, JSONObject data, String miniprogram_state, String lang) {
try {
Map<String, Object> map = new HashMap();
String access_token = this.authGetAccessToken();
map.put("access_token", access_token);
map.put("touser", touser);
map.put("template_id", template_id);
if (!Strings.isNullOrEmpty(page)) {
map.put("page", page);
}
map.put("data", data);
map.put("miniprogram_state", miniprogram_state);
map.put("lang", lang);
ResponseEntity responseEntity = RestTemplateUtils.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token
, JsonUtils.map2json(map), String.class);
log.info("小程序发送订阅消息:请求:{}响应:{}", JsonUtils.map2json(map), responseEntity.getBody().toString());
} catch (Exception e) {
log.error("{}", e);
}
}
public String payTransactionsJsapi(String description, String out_trade_no, String notify_url, Integer total, String openid)throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("mchid", mchid);
map.put("out_trade_no", out_trade_no);
map.put("appid", appid);
map.put("description", description);
map.put("notify_url", notify_url);
Map<String, Object> amountMap = new HashMap<>();
amountMap.put("total", total);
amountMap.put("currency", "CNY");
map.put("amount", amountMap);
Map<String, Object> payerMap = new HashMap<>();
payerMap.put("openid", openid);
map.put("payer", payerMap);
Map<String, String> headers=new HashMap<>();
String token=wxPayUtils.getToken("POST","https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",JsonUtils.map2json(map));
System.out.println("token => "+token);
headers.put("Authorization",token);
headers.put("Content-Type","application/json");
log.info("小程序jsapi下单接口:请求:{}", JsonUtils.map2json(map));
ResponseEntity responseEntity = RestTemplateUtils.post("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",headers, JsonUtils.map2json(map), String.class);
log.info("小程序jsapi下单接口响应:{}", responseEntity.getBody().toString());
Map<String, Object> rt = JsonUtils.json2map(responseEntity.getBody().toString());
return (String) rt.get("prepay_id");
}
public Map<String, Object> queryPayTransactionsByOutTradeNo(String out_trade_no) throws Exception{
String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + out_trade_no + "?mchid=" + mchid;
Map<String, String> headers=new HashMap<>();
String token=wxPayUtils.getToken("GET",url,"");
headers.put("Authorization",token);
ResponseEntity responseEntity = RestTemplateUtils.get(url, headers,String.class);
log.info("微信支付订单查询:请求:{}响应:{}", url, responseEntity.getBody().toString());
return JsonUtils.json2map(responseEntity.getBody().toString());
}
}
分页工具类
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
public class PageUtils<T extends Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
private int totalCount;
private int pageSize;
private int totalPage;
private int currPage;
private List<T> list;
public PageUtils(List<T> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
public PageUtils(IPage<T> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public PageUtils() {
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
原始的远程调用工具类(RestTemplate)
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
public class RestTemplateUtils {
private static final RestTemplate restTemplate;
public static final Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);
static {
restTemplate = new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(30)).setReadTimeout(Duration.ofSeconds(30)).build();
for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
}
}
}
public static <T> ResponseEntity<T> get(String url, Class<T> responseType) {
return restTemplate.getForEntity(url, responseType);
}
public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Object... uriVariables) {
return restTemplate.getForEntity(url, responseType, uriVariables);
}
public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.getForEntity(url, responseType, uriVariables);
}
public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return get(url, httpHeaders, responseType, uriVariables);
}
public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) {
HttpEntity<?> requestEntity = new HttpEntity<>(headers);
return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return get(url, httpHeaders, responseType, uriVariables);
}
public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<?> requestEntity = new HttpEntity<>(headers);
return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, Class<T> responseType) {
return restTemplate.postForEntity(url, HttpEntity.EMPTY, responseType);
}
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) {
return restTemplate.postForEntity(url, requestBody, responseType);
}
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
return restTemplate.postForEntity(url, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.postForEntity(url, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return post(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return post(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return post(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return post(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, Class<T> responseType, Object... uriVariables) {
return put(url, HttpEntity.EMPTY, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
return put(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
return put(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return put(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return put(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return put(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return put(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Object... uriVariables) {
return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Map<String, ?> uriVariables) {
return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return delete(url, httpHeaders, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return delete(url, httpHeaders, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return delete(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAll(headers);
return delete(url, httpHeaders, requestBody, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
return delete(url, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
}
public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables);
}
public static ResponseEntity exchange(String url, String method, String requestBody, String requestHeaders) throws Exception {
return RestTemplateUtils.exchange(url, method, requestBody, requestHeaders, null);
}
public static ResponseEntity exchange(String url, String method, String requestBody, String requestHeaders, LinkedMultiValueMap fileMap) throws Exception {
HttpEntity<Object> requestEntity = RestTemplateUtils.createHttpEntity(requestBody, requestHeaders,fileMap);
url=RestTemplateUtils.builderUrl(url, method, requestBody);
ResponseEntity responseEntity = RestTemplateUtils.getRestTemplate().exchange(url, HttpMethod.resolve(method),
requestEntity, String.class);
return responseEntity;
}
public static String builderUrl(String url, String method, String requestBody) {
if (HttpMethod.GET.name().equals(method) && !Strings.isNullOrEmpty(requestBody)) {
Map<String, String> uriVariables = JSON.parseObject(requestBody, Map.class);
if (CollectionUtils.isNotEmpty(uriVariables)) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : uriVariables.entrySet()) {
builder = builder.queryParam(entry.getKey(), entry.getValue());
}
url = builder.build().encode().toUri().toString();
}
}
return url;
}
public static RestTemplate getRestTemplate() {
return restTemplate;
}
public static HttpEntity createHttpEntity(String requestBody, String requestHeaders, LinkedMultiValueMap fileMap) {
HttpHeaders httpHeaders = new HttpHeaders();
if (!Strings.isNullOrEmpty(requestHeaders)) {
Map<String, String> requestHeadersMap = JSON.parseObject(requestHeaders, Map.class);
httpHeaders.setAll(requestHeadersMap);
if (requestHeaders.contains("form-data") || requestHeaders.contains("x-www-form-urlencoded")) {
LinkedMultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap();
if (!Strings.isNullOrEmpty(requestBody)) {
multiValueMap.setAll(JSON.parseObject(requestBody, Map.class));
}
if (requestHeaders.contains("multipart/form-data") && CollectionUtils.isNotEmpty(fileMap)) {
multiValueMap.addAll(fileMap);
}
return new HttpEntity(multiValueMap, httpHeaders);
}
}
return new HttpEntity(requestBody, httpHeaders);
}
public static String splitUrl(String host, String url) {
if (host.endsWith("/") && url.startsWith("/")) {
url = url.substring(1);
} else if (!host.endsWith("/") && !url.startsWith("/")) {
url = "/" + url;
}
return host + url;
}
}