Java按字典顺序排序请求参数

Java大约 1445 字
public String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
    String buff;
    try {
        List<Map.Entry<String, String>> infoIds = new ArrayList<>(paraMap.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()).compareTo(o2.getKey());
            }
        });

        // 构造URL 键值对的格式
        StringBuilder buf = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (!"".equals(item.getKey())) {
                String key = item.getKey();
                String val = item.getValue();
                if (urlEncode) {
                    val = URLEncoder.encode(val, "utf-8");
                }
                if (keyToLower) {
                    buf.append(key.toLowerCase()).append("=").append(val);
                } else {
                    buf.append(key).append("=").append(val);
                }
                buf.append("&");
            }

        }
        buff = buf.toString();
        if (!buff.isEmpty()) {
            buff = buff.substring(0, buff.length() - 1);
        }
    } catch (Exception e) {
        return null;
    }
    return buff;
}
阅读 1081 · 发布于 2019-04-08

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批