今天在做支付宝支付,关于异步通知结果,请求自己服务器的时候,需要接受支付宝的请求参数(类型为参数=值&参数=值&。。。),如果一个个取太麻烦,就用 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
xml转map如下
public static List
就能得到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的方式,如有瑕疵请多多指教