java url参数 转为 HashMap

Post 或 Get 的参数 

如:

&TalkDurAction=110&SrcTrunkName=&DstTrcunkName=&PinCode=&Status=ANSWERED&Type=Inbound 

 

用法

//HttpServletRequest request对象获取Post参数
BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null) {
    responseStrBuilder.append(inputStr);
    System.out.println("---------------------------------"+inputStr);
}
//获取POST参数 map
System.out.println("doPost() POST参数 " + responseStrBuilder.toString());
String strPostParam=responseStrBuilder.toString(); //POST参数
HashMap<String,String> mapPostParam = getUrlParams(responseStrBuilder.toString());
//取值
String strId = mapPostParam .get("Id").toString();

 

感谢 

原文

    //将url参数转换成map
    public static Map getUrlParams(String param) {
        Map map = new HashMap(0);
        if (StringUtils.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }

    //将map转换成url
    public static String getUrlParamsByMap(Map map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = org.apache.commons.lang.StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

 

posted @ 2022-04-21 13:44  海乐学习  阅读(912)  评论(0编辑  收藏  举报