开发随笔

微信支付-签名参数字典序排序

2017-10-20  本文已影响21人  8813d76fee36
public class ParamsAscSort {

    /**
     *  方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序),并且生成url参数串<
     * @param paramsMap 要排序的Map对象
     * @param urlEncode 是否需要URLENCODE
     * @param keyToLower 是否需要将Key转换为全小写 true:key转化成小写,false:不转化 
     * @return
     */
    public static String formatUrlMap(Map<String, String> paramsMap, boolean urlEncode, boolean keyToLower) {

        String buff = "";
        Map<String, String> tmpMap = paramsMap;

        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>>() {
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });

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

            if (StringUtils.isNotEmpty(buff)) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return buff;
    }

    public static void main(String[] args) {

        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("total_fee","200");
        paraMap.put("appid", "wxd678efh567hg6787");
        paraMap.put("body", "腾讯充值中心-QQ会员充值");
        paraMap.put("out_trade_no","20150806125346");
        String url = ParamsAscSort.formatUrlMap(paraMap, true, true);
        System.out.println(url);
    }
}

原文链接: http://blog.csdn.net/dong_18383219470/article/details/53636943

上一篇 下一篇

猜你喜欢

热点阅读