CusutUtil.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. package com.tyson.util;
  2. import org.json.JSONArray;
  3. import org.json.JSONObject;
  4. import org.springframework.http.HttpEntity;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.util.DigestUtils;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import javax.servlet.http.HttpServletRequest;
  10. import java.io.*;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import java.net.URLEncoder;
  14. import java.security.MessageDigest;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.text.DateFormat;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.util.*;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;
  22. /**
  23. * Decription:
  24. * 通用方法
  25. *
  26. * @author hzk
  27. * @Date 2021/10/21 17:45
  28. */
  29. public class CusutUtil {
  30. //当前时间加几天返回
  31. public static String SetTimeAddDay(int day) {
  32. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
  33. Calendar c = Calendar.getInstance();
  34. c.add(Calendar.DAY_OF_MONTH, day);
  35. return sf.format(c.getTime());
  36. }
  37. //当前时间加几月返回
  38. public static String SetTimeAddMonth(int Month) {
  39. SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
  40. Calendar c = Calendar.getInstance();
  41. c.add(Calendar.MONTH, Month);
  42. return sf.format(c.getTime());
  43. }
  44. //月份加任意
  45. public static String monthAddFrist(String date, int month) {
  46. DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  47. try {
  48. Calendar ct = Calendar.getInstance();
  49. ct.setTime(df.parse(date));
  50. ct.add(Calendar.MONTH, month);
  51. return df.format(ct.getTime());
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. return "";
  56. }
  57. //时间转时间戳(yyyy年MM月dd日) 毫秒级
  58. public static long dateTOtimeshap(String date) {
  59. String date_str = date + " 00:00:00";
  60. DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
  61. try {
  62. Date time = df.parse(date_str);
  63. long timestamp = time.getTime();
  64. return timestamp;
  65. } catch (Exception e) {
  66. try {
  67. Date time = df.parse(date);
  68. long timestamp = time.getTime();
  69. return timestamp;
  70. } catch (ParseException parseException) {
  71. parseException.printStackTrace();
  72. }
  73. }
  74. return 0;
  75. }
  76. //时间转时间戳(yyyyMMdd) 毫秒级
  77. public static long dateTOtimeshapYYMMDD(String date) {
  78. date += " 00:00:00";
  79. DateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
  80. try {
  81. Date time = df.parse(date);
  82. long timestamp = time.getTime();
  83. return timestamp;
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. return 0;
  88. }
  89. //时间转格式(yyyy/MM/dd/)
  90. public static String dateTOxieg(String date) {
  91. return date.replace("年", "").replace("月", "").replace("日", "");
  92. }
  93. //天数加任意
  94. public static String DayAddFrist(String date, int day) {
  95. DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  96. try {
  97. Calendar ct = Calendar.getInstance();
  98. ct.setTime(df.parse(date));
  99. ct.add(Calendar.DAY_OF_MONTH, day);
  100. return df.format(ct.getTime());
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. return "";
  105. }
  106. //根据云枢url获取refId
  107. public static String ByUrlGetRefId(String url) {
  108. String refId = url.substring(url.indexOf("?") + 7, url.indexOf("&"));
  109. return refId;
  110. }
  111. //String to html
  112. public static String strToHtml(String s) {
  113. if (s == null || s.equals("")) return "";
  114. s = s.replaceAll("&", "&");
  115. s = s.replaceAll("&lt;", "<");
  116. s = s.replaceAll("&gt;", ">");
  117. s = s.replaceAll(" ", "&nbsp;");
  118. return s;
  119. }
  120. //从头开始删除字符的方法
  121. public static String TruncateHeadString(String origin, int count) {
  122. if (origin == null || origin.length() < count) {
  123. return null;
  124. }
  125. char[] arr = origin.toCharArray();
  126. char[] ret = new char[arr.length - count];
  127. for (int i = 0; i < ret.length; i++) {
  128. ret[i] = arr[i + count];
  129. }
  130. return String.copyValueOf(ret);
  131. }
  132. //从尾部开始删除字符的方法
  133. public static String TruncateTailString(String origin, int count) {
  134. if (origin == null || origin.length() < count) {
  135. return null;
  136. }
  137. char[] arr = origin.toCharArray();
  138. char[] ret = new char[arr.length - count + 1];
  139. for (int i = 0; i < ret.length; i++) {
  140. ret[i] = arr[i];
  141. }
  142. return String.copyValueOf(ret);
  143. }
  144. /**
  145. * 获取现在时间
  146. *
  147. * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
  148. */
  149. public static String getNowDate() {
  150. Date currentTime = new Date();
  151. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  152. String dateString = formatter.format(currentTime);
  153. return dateString;
  154. }
  155. /**
  156. * @param string
  157. * @return 转换之后的内容
  158. * @Title: unicodeDecode
  159. * @Description: unicode解码 将Unicode的编码转换为中文
  160. */
  161. public static String unicodeDecode(String string) {
  162. Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
  163. Matcher matcher = pattern.matcher(string);
  164. char ch;
  165. while (matcher.find()) {
  166. ch = (char) Integer.parseInt(matcher.group(2), 16);
  167. string = string.replace(matcher.group(1), ch + "");
  168. }
  169. return string;
  170. }
  171. /**
  172. * 获取现在时间 -格式
  173. *
  174. * @return 返回时间类型 yyyyMMdd
  175. */
  176. public static String getNowDate(String gs) {
  177. Date currentTime = new Date();
  178. SimpleDateFormat formatter = new SimpleDateFormat(gs);
  179. String dateString = formatter.format(currentTime);
  180. return dateString;
  181. }
  182. //时间戳转时间 yyyyMMdd
  183. public static String getFormatDate(long times) {
  184. Date date = new Date(times);
  185. SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
  186. String dateString = formatter.format(date);
  187. return dateString;
  188. }
  189. //时间戳转时间 yyyyMMdd
  190. public static String getFormatDateYY(long times) {
  191. Date date = new Date(times);
  192. SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
  193. String dateString = formatter.format(date);
  194. return dateString;
  195. }
  196. //时间戳转时间 yyyyMM
  197. public static String getFormatDateMM(long times) {
  198. Date date = new Date(times);
  199. SimpleDateFormat formatter = new SimpleDateFormat("MM");
  200. String dateString = formatter.format(date);
  201. return dateString;
  202. }
  203. /**
  204. * 获取现在时间 -带时区
  205. *
  206. * @return 返回时间类型 yyyy-MM-dd'T'HH:mm:ssXXX
  207. */
  208. public static String getNowDate_TIMEZONE() {
  209. Date currentTime = new Date();
  210. Calendar cal = Calendar.getInstance(); // creates calendar
  211. cal.setTime(currentTime); // sets calendar time/date
  212. cal.add(Calendar.HOUR_OF_DAY, 2); // adds one hour
  213. currentTime = cal.getTime();//
  214. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
  215. String dateString = formatter.format(currentTime);
  216. return dateString;
  217. }
  218. /**
  219. * @Description : 时间格式转为yyyy-MM-dd
  220. * @Author : Lizzy
  221. * @Param :
  222. * @return : String
  223. * @Date : 2024/7/29 19:11
  224. */
  225. public static String getDate(long times) {
  226. Date date = new Date(times);
  227. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  228. String dateString = formatter.format(date);
  229. return dateString;
  230. }
  231. //获取jayy数组
  232. public static JSONArray getJayy(String s) {
  233. JSONObject jObj = new JSONObject(s);
  234. JSONArray content = new JSONArray();
  235. if (jObj.has("data")) {
  236. JSONObject jdata = new JSONObject(jObj.get("data").toString());
  237. content = new JSONArray(jdata.get("content").toString());
  238. }
  239. return content;
  240. }
  241. //月份加1
  242. public static String monthAddFrist(String date) {
  243. DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  244. try {
  245. Calendar ct = Calendar.getInstance();
  246. ct.setTime(df.parse(date));
  247. ct.add(Calendar.MONTH, +1);
  248. return df.format(ct.getTime());
  249. } catch (Exception e) {
  250. e.printStackTrace();
  251. }
  252. return "";
  253. }
  254. //返回成功格式
  255. public static String SuccessReturnJsonString(int code, String data, String... types) {
  256. for (String type : types) {
  257. if (type.toLowerCase().contains("str")) data = "\"" + data + "\"";
  258. }
  259. return "{\"code\":" + code + ",\"message\":\"\",\"response\":" + data + ",\"success\":true}";
  260. }
  261. public static Object jsonByHas(JSONObject jo, String key) {
  262. if (jo.has(key)) {
  263. return jo.get(key);
  264. }
  265. return null;
  266. }
  267. //返回失败格式
  268. public static String ErrorReturnJsonString(int code, String message, String... types) {
  269. if (types.length == 0) {
  270. message = "\"" + message + "\"";
  271. }
  272. return "{\"code\":" + code + ",\"message\":" + message + ",\"response\":null,\"success\":false}";
  273. }
  274. //返回json中需要的参
  275. public static String getJsonValue(JSONObject iter, String jpath) {
  276. String[] json_vals = jpath.split("\\.");
  277. for (int i = 0; i < json_vals.length; i++) {
  278. if (i + 1 >= json_vals.length)
  279. return iter.has(json_vals[i]) ? iter.get(json_vals[i]).toString() : "";
  280. iter = new JSONObject(iter.get(json_vals[i]).toString());
  281. }
  282. return "";
  283. }
  284. //计算两个时间相差的秒数
  285. public static long getTime(String startTime, String endTime) {
  286. try {
  287. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  288. long eTime = df.parse(endTime).getTime();
  289. long sTime = df.parse(startTime).getTime();
  290. long diff = (eTime - sTime) / 1000;
  291. return diff;
  292. } catch (Exception ex) {
  293. ex.printStackTrace();
  294. }
  295. return 0;
  296. }
  297. /**
  298. * 生成32位随机数
  299. *
  300. * @return
  301. */
  302. public static String random32() {
  303. Random rand = new Random();
  304. StringBuffer sb = new StringBuffer();
  305. for (int i = 1; i <= 32; i++) {
  306. int randNum = rand.nextInt(9) + 1;
  307. String num = randNum + "";
  308. sb = sb.append(num);
  309. }
  310. String random = String.valueOf(sb);
  311. return random;
  312. }
  313. //转义字符供getJsonValue使用
  314. private static String tpath = "data.%s.";
  315. public static String getJpath(String Name) {
  316. return getJpath("", Name);
  317. }
  318. public static String getJpath(String Name, String params) {
  319. return String.format(tpath, params) + Name;
  320. }
  321. //获取前端发送的json字符串
  322. public static String getPostString(HttpServletRequest request) {
  323. String s = "";
  324. InputStream in = null;
  325. BufferedInputStream bin = null;
  326. try {
  327. in = request.getInputStream();
  328. bin = new BufferedInputStream(in);
  329. int len = 0;
  330. byte[] b = new byte[1024];
  331. while ((len = bin.read(b)) != -1) {
  332. s += new String(b, 0, len);
  333. }
  334. } catch (IOException e) {
  335. e.printStackTrace();
  336. } finally {
  337. try {
  338. bin.close();
  339. } catch (IOException e) {
  340. e.printStackTrace();
  341. }
  342. try {
  343. in.close();
  344. } catch (IOException e) {
  345. e.printStackTrace();
  346. }
  347. return s;
  348. }
  349. }
  350. //Authorization
  351. public static HttpEntity<String> JsonToHttpEntity(JSONObject json, String... Authorization) {
  352. HttpHeaders headers = new HttpHeaders();
  353. MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
  354. headers.setContentType(type);
  355. if (Authorization.length > 0) {
  356. headers.add("Authorization", Authorization[0]);
  357. }
  358. headers.add("Accept", MediaType.APPLICATION_JSON.toString());
  359. HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
  360. return formEntity;
  361. }
  362. public static HttpEntity<String> HttpEntity_headers(JSONObject json, HashMap<String, String> map) {
  363. HttpHeaders headers = new HttpHeaders();
  364. MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
  365. headers.setContentType(type);
  366. if (map.size() > 0) {
  367. for (Map.Entry entry : map.entrySet()) {
  368. headers.add(entry.getKey().toString(), entry.getValue().toString());
  369. }
  370. }
  371. headers.add("Accept", MediaType.APPLICATION_JSON.toString());
  372. HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
  373. return formEntity;
  374. }
  375. //加密方法
  376. /**
  377. * 传入文本内容,返回 SHA-256 串
  378. *
  379. * @param strText
  380. * @return
  381. */
  382. public static String SHA256(final String strText) {
  383. return SHA(strText, "SHA-256");
  384. }
  385. /**
  386. * 传入文本内容,返回 SHA-512 串
  387. *
  388. * @param strText
  389. * @return
  390. */
  391. public static String SHA512(final String strText) {
  392. return SHA(strText, "SHA-512");
  393. }
  394. /**
  395. * 字符串 SHA 加密
  396. *
  397. * @param strType
  398. * @return
  399. */
  400. private static String SHA(final String strText, final String strType) {
  401. // 返回值
  402. String strResult = null;
  403. // 是否是有效字符串
  404. if (strText != null && strText.length() > 0) {
  405. try {
  406. // SHA 加密开始
  407. // 创建加密对象 并傳入加密類型
  408. MessageDigest messageDigest = MessageDigest.getInstance(strType);
  409. // 传入要加密的字符串
  410. messageDigest.update(strText.getBytes());
  411. // 得到 byte 類型结果
  412. byte byteBuffer[] = messageDigest.digest();
  413. // 將 byte 轉換爲 string
  414. StringBuffer strHexString = new StringBuffer();
  415. // 遍歷 byte buffer
  416. for (int i = 0; i < byteBuffer.length; i++) {
  417. String hex = Integer.toHexString(0xff & byteBuffer[i]);
  418. if (hex.length() == 1) {
  419. strHexString.append('0');
  420. }
  421. strHexString.append(hex);
  422. }
  423. // 得到返回結果
  424. strResult = strHexString.toString();
  425. } catch (NoSuchAlgorithmException e) {
  426. e.printStackTrace();
  427. }
  428. }
  429. return strResult;
  430. }
  431. //用户密码加密封装
  432. public static String hash_password(String password) {
  433. return SHA256(SHA512(password));
  434. }
  435. public static String md5(String body) {
  436. String md5 = "";
  437. try {
  438. md5 = DigestUtils.md5DigestAsHex(body.getBytes());
  439. } catch (Exception e) {
  440. e.printStackTrace();
  441. }
  442. return md5;
  443. }
  444. /**
  445. * 去除前后指定字符
  446. *
  447. * @param args 目标字符串
  448. * @param beTrim 要删除的指定字符
  449. * @return 删除之后的字符串
  450. * 调用示例:System.out.println(trim("$$abc $","$"));
  451. */
  452. public static String trim(String args, char beTrim) {
  453. int st = 0;
  454. int len = args.length();
  455. char[] val = args.toCharArray();
  456. char sbeTrim = beTrim;
  457. while ((st < len) && (val[st] <= sbeTrim)) {
  458. st++;
  459. }
  460. while ((st < len) && (val[len - 1] <= sbeTrim)) {
  461. len--;
  462. }
  463. return ((st > 0) || (len < args.length())) ? args.substring(st, len) : args;
  464. }
  465. /**
  466. * MultipartFile 转 File
  467. *
  468. * @param file
  469. * @throws Exception
  470. */
  471. public static File multipartFileToFile(MultipartFile file) throws Exception {
  472. File toFile = null;
  473. if (file.equals("") || file.getSize() <= 0) {
  474. file = null;
  475. } else {
  476. InputStream ins = null;
  477. ins = file.getInputStream();
  478. toFile = new File(new Date().getTime() + "-" + UUID.randomUUID() + "." + file.getOriginalFilename().split("\\.")[1]);
  479. inputStreamToFile(ins, toFile);
  480. ins.close();
  481. }
  482. return toFile;
  483. }
  484. //获取流文件
  485. private static void inputStreamToFile(InputStream ins, File file) {
  486. try {
  487. OutputStream os = new FileOutputStream(file);
  488. int bytesRead = 0;
  489. byte[] buffer = new byte[8192];
  490. while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
  491. os.write(buffer, 0, bytesRead);
  492. }
  493. os.close();
  494. ins.close();
  495. } catch (Exception e) {
  496. e.printStackTrace();
  497. }
  498. }
  499. /**
  500. * 删除本地临时文件
  501. *
  502. * @param file
  503. */
  504. public static void delteTempFile(File file) {
  505. if (file != null) {
  506. File del = new File(file.toURI());
  507. del.delete();
  508. }
  509. }
  510. /**
  511. * 根据经纬度查询
  512. *
  513. * @param log
  514. * @param lat
  515. * @return
  516. */
  517. public static String getAdd(String log, String lat) {
  518. //lat 小 log 大
  519. //参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
  520. String urlString = "http://api.map.baidu.com/geocoder/v2/?ak=0EXAjYp9hii1DrK3Tuda8efu9vivslcX&callback=renderReverse&location=" + lat + "," + log + "&output=json&pois=1";
  521. String res = "";
  522. try {
  523. URL url = new URL(urlString);
  524. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  525. conn.setDoOutput(true);
  526. conn.setRequestMethod("POST");
  527. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  528. String line;
  529. while ((line = in.readLine()) != null) {
  530. res += line + "\n";
  531. }
  532. in.close();
  533. } catch (Exception e) {
  534. System.out.println("error in wapaction,and e is " + e.getMessage());
  535. }
  536. System.out.println(res);
  537. return res;
  538. }
  539. public static void main(String[] args) {
  540. /* System.out.println(getAdd(119.0478515625+"",31.5785354265+""));*/
  541. //System.out.println(addressResolution("河南省仙桃市"));
  542. double b = (double) 560 / 100;
  543. System.out.println(b);
  544. String add = CusutUtil.getAdd("119.0478515625", "31.5785354265");
  545. System.out.println(add);
  546. }
  547. /**
  548. * 根据url 拉取文件
  549. *
  550. * @param url
  551. * @return
  552. * @throws Exception
  553. */
  554. public static File getFile(String url) throws Exception {
  555. File file = null;
  556. try {
  557. HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
  558. httpUrl.connect();
  559. file = CusutUtil.inputStreamToFile(httpUrl.getInputStream(), "url.png");
  560. httpUrl.disconnect();
  561. } catch (Exception e) {
  562. e.printStackTrace();
  563. }
  564. return file;
  565. }
  566. /**
  567. * 工具类
  568. * inputStream 转 File
  569. */
  570. public static File inputStreamToFile(InputStream ins, String name) throws Exception {
  571. File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
  572. if (file.exists()) {
  573. return file;
  574. }
  575. OutputStream os = new FileOutputStream(file);
  576. int bytesRead;
  577. int len = 8192;
  578. byte[] buffer = new byte[len];
  579. while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
  580. os.write(buffer, 0, bytesRead);
  581. }
  582. os.close();
  583. ins.close();
  584. return file;
  585. }
  586. public static String isJson(String str) {
  587. String result = "false";
  588. if (str != null) {
  589. str = str.trim();
  590. if (str.startsWith("{") && str.endsWith("}")) {
  591. result = "json";
  592. } else if (str.startsWith("[") && str.endsWith("]")) {
  593. result = "jarray";
  594. }
  595. }
  596. return result;
  597. }
  598. public static String jsonTOxml(JSONObject jo) {
  599. Iterator iterator = jo.keys();
  600. String xmlStr = "<xml>";
  601. while (iterator.hasNext()) {
  602. String key = (String) iterator.next();
  603. String val = jo.get(key).toString();
  604. xmlStr += "\n<" + key + ">" + val + "</" + key + ">";
  605. }
  606. return xmlStr + "\n</xml>";
  607. }
  608. /**
  609. * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序),并且生成参数串<br>
  610. * 实现步骤: <br>
  611. *
  612. * @param paraMap 要排序的Map对象
  613. * @param urlEncode 是否需要URLENCODE
  614. * @param keyToLower 是否需要将Key转换为全小写
  615. * true:key转化成小写,false:不转化
  616. * @return
  617. */
  618. public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
  619. String buff = "";
  620. Map<String, String> tmpMap = paraMap;
  621. try {
  622. List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
  623. // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
  624. Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
  625. @Override
  626. public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
  627. return (o1.getKey()).toString().compareTo(o2.getKey());
  628. }
  629. });
  630. // 构造返回字符串键值对的格式
  631. StringBuilder buf = new StringBuilder();
  632. for (Map.Entry<String, String> item : infoIds) {
  633. if (item.getKey() != "") {
  634. String key = item.getKey();
  635. String val = item.getValue();
  636. if (urlEncode) {
  637. val = URLEncoder.encode(val, "utf-8");
  638. }
  639. if (keyToLower) {
  640. buf.append(key.toLowerCase() + "=" + val);
  641. } else {
  642. buf.append(key + "=" + val);
  643. }
  644. buf.append("&");
  645. }
  646. }
  647. buff = buf.toString();
  648. if (buff.isEmpty() == false) {
  649. buff = buff.substring(0, buff.length() - 1);
  650. }
  651. } catch (Exception e) {
  652. return null;
  653. }
  654. return buff;
  655. }
  656. public static String getRandomString(int length) {
  657. //1. 定义一个字符串(A-Z,a-z,0-9)即62个数字字母;
  658. String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
  659. //2. 由Random生成随机数
  660. Random random = new Random();
  661. StringBuffer sb = new StringBuffer();
  662. //3. 长度为几就循环几次
  663. for (int i = 0; i < length; ++i) {
  664. //从62个的数字或字母中选择
  665. int number = random.nextInt(62);
  666. //将产生的数字通过length次承载到sb中
  667. sb.append(str.charAt(number));
  668. }
  669. //将承载的字符转换成字符串
  670. return sb.toString();
  671. }
  672. }