1
0

CommonUtil.java 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package com.kmall.api.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.kmall.common.utils.CharUtil;
  4. import com.kmall.common.utils.DateUtils;
  5. import com.kmall.common.utils.wechat.MyX509TrustManager;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import sun.misc.BASE64Decoder;
  9. import sun.misc.BASE64Encoder;
  10. import javax.net.ssl.HttpsURLConnection;
  11. import javax.net.ssl.SSLContext;
  12. import javax.net.ssl.SSLSocketFactory;
  13. import javax.net.ssl.TrustManager;
  14. import java.io.*;
  15. import java.math.BigDecimal;
  16. import java.net.ConnectException;
  17. import java.net.URL;
  18. import java.security.MessageDigest;
  19. import java.util.Calendar;
  20. import java.util.Date;
  21. public class CommonUtil {
  22. private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
  23. /**
  24. * 发送https请求
  25. *
  26. * @param requestUrl 请求地址
  27. * @param requestMethod 请求方式(GET、POST)
  28. * @param outputStr 提交的数据
  29. * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
  30. */
  31. public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
  32. JSONObject jsonObject = null;
  33. try {
  34. // 创建SSLContext对象,并使用我们指定的信任管理器初始化
  35. TrustManager[] tm = {new MyX509TrustManager()};
  36. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  37. sslContext.init(null, tm, new java.security.SecureRandom());
  38. // 从上述SSLContext对象中得到SSLSocketFactory对象
  39. SSLSocketFactory ssf = sslContext.getSocketFactory();
  40. URL url = new URL(requestUrl);
  41. HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  42. conn.setSSLSocketFactory(ssf);
  43. conn.setDoOutput(true);
  44. conn.setDoInput(true);
  45. conn.setUseCaches(false);
  46. // 设置请求方式(GET/POST)
  47. conn.setRequestMethod(requestMethod);
  48. // 当outputStr不为null时向输出流写数据
  49. if (null != outputStr) {
  50. OutputStream outputStream = conn.getOutputStream();
  51. // 注意编码格式
  52. outputStream.write(outputStr.getBytes("UTF-8"));
  53. outputStream.close();
  54. }
  55. // 从输入流读取返回内容
  56. InputStream inputStream = conn.getInputStream();
  57. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  58. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  59. String str = null;
  60. StringBuffer buffer = new StringBuffer();
  61. while ((str = bufferedReader.readLine()) != null) {
  62. buffer.append(str);
  63. }
  64. // 释放资源
  65. bufferedReader.close();
  66. inputStreamReader.close();
  67. inputStream.close();
  68. inputStream = null;
  69. conn.disconnect();
  70. jsonObject = JSONObject.parseObject(buffer.toString());
  71. } catch (ConnectException ce) {
  72. log.error("连接超时:{}", ce);
  73. } catch (Exception e) {
  74. log.error("https请求异常:{}", e);
  75. }
  76. return jsonObject;
  77. }
  78. /**
  79. * 生成订单的编号order_sn
  80. */
  81. public static String generateOrderNumber() {
  82. Calendar cal = Calendar.getInstance();
  83. cal.setTime(new Date());
  84. String timeStr = DateUtils.format(cal.getTime(), DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
  85. return timeStr + CharUtil.getRandomNum(4);
  86. }
  87. public static String getSha1(String str) {
  88. if (str == null || str.length() == 0) {
  89. return null;
  90. }
  91. char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  92. 'a', 'b', 'c', 'd', 'e', 'f'};
  93. try {
  94. MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
  95. mdTemp.update(str.getBytes("UTF-8"));
  96. byte[] md = mdTemp.digest();
  97. int j = md.length;
  98. char buf[] = new char[j * 2];
  99. int k = 0;
  100. for (int i = 0; i < j; i++) {
  101. byte byte0 = md[i];
  102. buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
  103. buf[k++] = hexDigits[byte0 & 0xf];
  104. }
  105. return new String(buf);
  106. } catch (Exception e) {
  107. // TODO: handle exception
  108. return null;
  109. }
  110. }
  111. /**
  112. * 地球半径
  113. */
  114. private final static double EARTH_RADIUS = 6378.137;
  115. /**
  116. * 计算地球的两个点之间的距离,单位km
  117. *
  118. * @param _lat1
  119. * @param _lon1
  120. * @param _lat2
  121. * @param _lon2
  122. * @return
  123. */
  124. public static double getDistance(double _lat1, double _lon1, double _lat2, double _lon2) {
  125. double lat1 = (Math.PI / 180) * _lat1;
  126. double lat2 = (Math.PI / 180) * _lat2;
  127. double lon1 = (Math.PI / 180) * _lon1;
  128. double lon2 = (Math.PI / 180) * _lon2;
  129. double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * EARTH_RADIUS;
  130. if (d < 100) {
  131. return new BigDecimal(d).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
  132. } else {
  133. return new BigDecimal(d).setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
  134. }
  135. }
  136. // 加密
  137. public static String encode(String str) {
  138. byte[] b = null;
  139. String s = null;
  140. try {
  141. b = str.getBytes("utf-8");
  142. } catch (UnsupportedEncodingException e) {
  143. e.printStackTrace();
  144. }
  145. if (b != null) {
  146. s = new BASE64Encoder().encode(b);
  147. }
  148. return s;
  149. }
  150. // 解密
  151. public static String decode(String s) {
  152. byte[] b = null;
  153. String result = null;
  154. if (s != null) {
  155. BASE64Decoder decoder = new BASE64Decoder();
  156. try {
  157. b = decoder.decodeBuffer(s);
  158. result = new String(b, "utf-8");
  159. } catch (Exception e) {
  160. e.printStackTrace();
  161. }
  162. }
  163. return result;
  164. }
  165. }