Java將Map物件按字典序排列,並且封裝成URL的工具類
阿新 • • 發佈:2019-02-04
/**
*
* 方法用途: 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序),並且生成url引數串<br>
* 實現步驟: <br>
*
* @param paraMap 要排序的Map物件
* @param urlEncode 是否需要URLENCODE
* @param keyToLower 是否需要將Key轉換為全小寫
* true:key轉化成小寫,false:不轉化
* @return
*/
public static String formatParaMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)
{
String buff = "";
Map<String, String> tmpMap = paraMap;
try
{
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
// 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序)
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
{
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
// 構造URL 鍵值對的格式
StringBuilder buf = new StringBuilder();
for (Map.Entry<String, String> item : infoIds)
{
if (StringUtils.isNotBlank(item.getKey()))
{
String key = item.getKey();
String val = item.getValue();
if (urlEncode)
{
val = encode(val, CommonConstant.ENCODING_UTF8);
}
if (keyToLower)
{
buf.append(key.toLowerCase() + "=" + val);
} else
{
buf.append(key + "=" + val);
}
buf.append("&");
}
}
buff = buf.toString();
if (buff.isEmpty() == false)
{
buff = buff.substring(0, buff.length() - 1);
}
} catch (Exception e)
{
throw new SysException(e.getMessage());
}
return buff;
}
*
* 方法用途: 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序),並且生成url引數串<br>
* 實現步驟: <br>
*
* @param paraMap 要排序的Map物件
* @param urlEncode 是否需要URLENCODE
* @param keyToLower 是否需要將Key轉換為全小寫
* true:key轉化成小寫,false:不轉化
* @return
*/
public static String formatParaMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)
{
String buff = "";
Map<String, String> tmpMap = paraMap;
try
{
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
// 對所有傳入引數按照欄位名的 ASCII 碼從小到大排序(字典序)
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
{
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
// 構造URL 鍵值對的格式
StringBuilder buf = new StringBuilder();
for (Map.Entry<String, String> item : infoIds)
{
if (StringUtils.isNotBlank(item.getKey()))
{
String key = item.getKey();
String val = item.getValue();
if (urlEncode)
{
val = encode(val, CommonConstant.ENCODING_UTF8);
}
if (keyToLower)
{
buf.append(key.toLowerCase() + "=" + val);
} else
{
buf.append(key + "=" + val);
}
buf.append("&");
}
}
buff = buf.toString();
if (buff.isEmpty() == false)
{
buff = buff.substring(0, buff.length() - 1);
}
} catch (Exception e)
{
throw new SysException(e.getMessage());
}
return buff;
}