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

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

public static Map<String, String> toMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> 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<String, String> retMap = new TreeMap<String, String>();
		// 解析xml成map
		List<Map<String, String>> maplist = CommonMethodUtil.xmlToMap(sb
				.toString());
		for (Map<String, String> map : maplist) {
			for (Entry<String, String> skey : map.entrySet()) {
				retMap.put(skey.getKey(), skey.getValue());
			}
		} }

xml转map如下

public static List<Map<String,String>> xmlToMap(String xmlStr){
		List<Map<String,String>> maplist=new ArrayList<Map<String,String>>();
		if(!"".equals(xmlStr) && null!=xmlStr){
			try {
				Document document = DocumentHelper.parseText(xmlStr);
				Element rootElement=document.getRootElement();
				@SuppressWarnings("unchecked")
				Iterator<Element> iterator=rootElement.elements().iterator();
				while(iterator.hasNext()){
					Element element=iterator.next();
					@SuppressWarnings("rawtypes")
					List rowlist=element.attributes();
					@SuppressWarnings("rawtypes")
					Iterator iter =rowlist.iterator();
					Map<String,String> map=new HashMap<String, String>();
//					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<String, Object> 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的方式,如有瑕疵请多多指教


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于JAVA调用接口传递参数和接收JSON数据,可以通过以下步骤来实现: 1.导入相关的依赖包,例如Apache HttpClient、FastJSON等。 2.构造请求参数换为JSON格式。可以使用FastJSON将Java对象换为JSON字符串。 3.创建HttpClient对象,并设置请求方法、请求头、请求体等参数请求方法为POST,请求头中需要设置Content-Type为application/json。 4.执行请求并获取响应。可以使用HttpClient执行请求,并获取响应。响应中包含了接口返回的JSON数据。 5.解析JSON数据并处理结果。可以使用FastJSON将JSON字符串换为Java对象,然后根据接口返回的数据进行相应的处理。 以下是示例代码: ```java import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class InterfaceTest { public static void main(String[] args) throws IOException { // 构造请求参数 Map<String, Object> params = new HashMap<String, Object>(); params.put("username", "test"); params.put("password", "123456"); String jsonStr = JSON.toJSONString(params); // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/api/login"); // 设置请求头 httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // 设置请求体 StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); httpPost.setEntity(stringEntity); // 执行请求并获取响应 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); String responseStr = EntityUtils.toString(httpEntity, "UTF-8"); // 解析JSON数据并处理结果 JSONObject jsonObject = JSON.parseObject(responseStr); int code = jsonObject.getIntValue("code"); String message = jsonObject.getString("message"); if (code == 0) { // 登录成功 String token = jsonObject.getString("token"); System.out.println("登录成功,Token为:" + token); } else { // 登录失败 System.out.println("登录失败,原因:" + message); } // 关闭HttpClient和响应流 httpResponse.close(); httpClient.close(); } } ``` 注意:以上代码仅供参考,具体实现需要根据接口的具体要求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值