java关于请求参数转Map的记录

今天在做支付宝支付,关于异步通知结果,请求自己服务器的时候,需要接受支付宝的请求参数(类型为参数=值&参数=值&。。。),如果一个个取太麻烦,就用 request.getParameterMap()方法把参数放到了Map中,方便对参数做操作代码如下

public static Map toMap(HttpServletRequest request) {
        Map params = new HashMap();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决,这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

返回了一个map集合,正是我想要的东西,取值很方便,突然想到之前做微信支付的时候,接受的请求参数是XML格式,用的是对流操作取参然后转map的,上代码

public void returnNotify(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(
				inputStream, Consts.UTF_8));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		SortedMap retMap = new TreeMap();
		// 解析xml成map
		List> maplist = CommonMethodUtil.xmlToMap(sb
				.toString());
		for (Map map : maplist) {
			for (Entry skey : map.entrySet()) {
				retMap.put(skey.getKey(), skey.getValue());
			}
		} }

xml转map如下

public static List> xmlToMap(String xmlStr){
		List> maplist=new ArrayList>();
		if(!"".equals(xmlStr) && null!=xmlStr){
			try {
				Document document = DocumentHelper.parseText(xmlStr);
				Element rootElement=document.getRootElement();
				@SuppressWarnings("unchecked")
				Iterator iterator=rootElement.elements().iterator();
				while(iterator.hasNext()){
					Element element=iterator.next();
					@SuppressWarnings("rawtypes")
					List rowlist=element.attributes();
					@SuppressWarnings("rawtypes")
					Iterator iter =rowlist.iterator();
					Map map=new HashMap();
//					map.put(element.getName(), element.getName());
					
					while(iter.hasNext()){
						AbstractAttribute elementAttr = (AbstractAttribute) iter.next();
						map.put(elementAttr.getName(), elementAttr.getValue());
					}
					map.put(element.getName(), element.getText());
					maplist.add(map);
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return maplist;
	}

就能得到map去操作咯,是不是很方便,

另外如果传递的参数为json格式可以用下面方式转map,因为map本身和json就类似

package com.mockCommon.controller.mock.youbi;  
  
import java.util.Map;  
  
import org.apache.commons.lang.StringUtils;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.mockCommon.constant.LogConstant;  
import com.mockCommon.service.mock.youbi.impl.SearchCarModelMockServiceImpl;  
  
@Controller  
public class SearchCarModelMockController {  
    @Autowired  
    private SearchCarModelMockServiceImpl searchCarModelMockServiceImpl;  
      
    @RequestMapping(value = "/vehicle", method = RequestMethod.POST)  
    @ResponseBody  
    public String searchCarModel(@RequestBody Map params){  
        LogConstant.runLog.info("[JiekouSearchCarModel]parameter license_no:" + params.get("license_no") + ", license_owner:" + params.get("license_owner") + ", city_code:" + params.get("city_code"));  
        String result = null;  
        if(params.get("license_no")==null || params.get("license_owner")==null|| params.get("city_code")==null){  
            return "传递参数不正确";  
        }  
        result = searchCarModelMockServiceImpl.getResult(params.get("license_no").toString(), params.get("license_owner").toString(), params.get("city_code").toString());  
        return result;  
    }  
}  

好了 以上就是三种常见的参数转map的方式,如有瑕疵请多多指教


你可能感兴趣的:(JAVA)