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;
|
}
|
|
|
|
}
|