欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UrlEncode后的参数如何在请求体中拿到并且转换成字符

程序员文章站 2022-05-24 18:22:22
...

由于服务间调用,参数容易乱码,所以在请求的时候将参数encode,然后到被请求方解析成想要的格式

  /**
     * 绿盾
     * @param param
     * @return
     */
    @SuppressWarnings("unused")
	@RequestMapping(value = "/chatMonitorForLD", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Object getChatMonitor(HttpServletRequest request) {
    	    Map<String, Object> param=getMapByParms(request);
            Map<String, Object> res = new HashMap<String, Object>();
        	return JSONObject.toJSON(res);
    }
    
    /**
     * 获取POST请求中Body参数 返回参数
     * @param request
     * @return 字符串
     */
    @SuppressWarnings("unchecked")
	public static Map<String,Object>  getMapByParms(HttpServletRequest request) {
    	Map<String,Object> result=new HashMap<String,Object>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String json="";
		try {
		    //将请求的参数Decode成json字符串
			json = java.net.URLDecoder.decode(sb.toString(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if(json.length()>0){
        	result=(HashMap<String,Object>)JsonUtil.fromJsons(json,HashMap.class);
        }
        return result;

	
       }