map按key排序并转化成urlKeyValue字符串形式

xiaoxiao2021-02-28  105

public class ParameterUtils { public static Map<String, String> getRequestParameters( HttpServletRequest request) { Map<String, String> map = new HashMap<String, String>(); Map<String, String[]> paramMap = request.getParameterMap(); for (Iterator<String> it = paramMap.keySet().iterator(); it.hasNext();) { String key = it.next(); map.put(key, paramMap.get(key)[0]); } return map; } public static String getRequestQueryString(Map<String, String> params) { Map<String, String> resultMap = sortMapByKey(params); //按Key进行排序 StringBuffer buffer = new StringBuffer(); for (Iterator<String> it = resultMap.keySet().iterator(); it.hasNext();) { String key = it.next(); //当jsonp跨域访问时会出现该参数 if(StringUtils.equalsIgnoreCase("callback", key)){ continue; } buffer.append(key + "=" + resultMap.get(key) + "&"); } return buffer.substring(0, buffer.length()-1); } /** * 使用 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; } }

MapKeyComparator

public class MapKeyComparator implements Comparator<String>{ public int compare(String str1, String str2) { return str1.compareTo(str2); } }
转载请注明原文地址: https://www.6miu.com/read-33258.html

最新回复(0)