wangrong
2021-11-24 130b72d6c5734f8acaac0214b6dfe5c8bfa319c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.demo.utils;
 
 
import java.util.*;
 
 
public class untils {
 
    /** 
      * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
      * @param params 需要排序并参与字符拼接的参数组
      * @return 拼接后字符串
      * @throws UnsupportedEncodingException 
      */
    public static String createLinkString(Map<String, String> params) {
 
        
        Map<String, String> mapparams =sortMapByKey(params);
        if (mapparams == null) {
            return "";
        }
        List<String> keys = new ArrayList<String>(mapparams.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = mapparams.get(key);
            if (i == keys.size() - 1) {////拼接时,不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }
    
     /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
 
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
 
        sortMap.putAll(map);
 
        return sortMap;
    }
    
    
    
}