(转)获取 request 中用POST方式"Content-type"是"application/x-www-form-urlencoded;charset=utf-8"发送的 json 数据

request中发送json数据用post方式发送Content-type用application/json;charset=utf-8方式发送的话,直接用springMVC的@RequestBody标签接收后面跟实体对象就行了,spring会帮你自动拼装成对象,如果Content-type设置成application/x-www-form-urlencoded;charset=utf-8就不能用spring的东西了,只能以常规的方式获取json串了

方式一:通过流的方式

  1. import java.io.IOException;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5.   
  6. /**       
  7.  * request 对象的相关操作 
  8.  * @author zhangtengda         
  9.  * @version 1.0       
  10.  * @created 2015年5月2日 下午8:25:43      
  11.  */         
  12. public class GetRequestJsonUtils {  
  13.   
  14.     /*** 
  15.      * 获取 request 中 json 字符串的内容 
  16.      *  
  17.      * @param request 
  18.      * @return : <code>byte[]</code> 
  19.      * @throws IOException 
  20.      */  
  21.     public static String getRequestJsonString(HttpServletRequest request)  
  22.             throws IOException {  
  23.         String submitMehtod = request.getMethod();  
  24.         // GET  
  25.         if (submitMehtod.equals("GET")) {  
  26.             return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", """);  
  27.         // POST  
  28.         } else {  
  29.             return getRequestPostStr(request);  
  30.         }  
  31.     }  
  32.   
  33.     /**       
  34.      * 描述:获取 post 请求的 byte[] 数组 
  35.      * <pre> 
  36.      * 举例: 
  37.      * </pre> 
  38.      * @param request 
  39.      * @return 
  40.      * @throws IOException       
  41.      */  
  42.     public static byte[] getRequestPostBytes(HttpServletRequest request)  
  43.             throws IOException {  
  44.         int contentLength = request.getContentLength();  
  45.         if(contentLength<0){  
  46.             return null;  
  47.         }  
  48.         byte buffer[] = new byte[contentLength];  
  49.         for (int i = 0; i < contentLength;) {  
  50.   
  51.             int readlen = request.getInputStream().read(buffer, i,  
  52.                     contentLength - i);  
  53.             if (readlen == -1) {  
  54.                 break;  
  55.             }  
  56.             i += readlen;  
  57.         }  
  58.         return buffer;  
  59.     }  
  60.   
  61.     /**       
  62.      * 描述:获取 post 请求内容 
  63.      * <pre> 
  64.      * 举例: 
  65.      * </pre> 
  66.      * @param request 
  67.      * @return 
  68.      * @throws IOException       
  69.      */  
  70.     public static String getRequestPostStr(HttpServletRequest request)  
  71.             throws IOException {  
  72.         byte buffer[] = getRequestPostBytes(request);  
  73.         String charEncoding = request.getCharacterEncoding();  
  74.         if (charEncoding == null) {  
  75.             charEncoding = "UTF-8";  
  76.         }  
  77.         return new String(buffer, charEncoding);  
  78.     }  
  79.   
  80. }  
//在controll中进行调用
String content = HttpJsonUtils.getPostByApplicationForm(request);
			LOGGER.info("content*************" + content);
			JSONObject jsObject = JSONObject.fromObject(content);
			try {
				ipbegin = jsObject.getLong("ipbegin");
				ipend = jsObject.getLong("ipend");
				province = jsObject.getString("province");
				isopen = jsObject.getString("isopen");
				opertime = jsObject.getString("opertime");
				sign = jsObject.getString("sign");
			} catch (Exception e) {
				// TODO: handle exception
				e.getMessage();
				LOGGER.info("发生错误*****" + e.getMessage());
			}
			LOGGER.info("ipbegin********************************" + ipbegin);
			LOGGER.info("ipend********************************" + ipend);
			LOGGER.info("province********************************" + province);
			LOGGER.info("isopen********************************" + isopen);
			LOGGER.info("opertime********************************" + opertime);
			LOGGER.info("sign********************************" + sign);

  

方式二:通过获取Map的方式处理

这种刚方式存在弊端,如果json数据中存在=号,数据会在等号的地方断掉,后面的数据会被存储成map的values,需要重新拼装key和values的值,拼装成原来的json串

  1. /**  
  2.      * 方法说明 :通过获取map的方式 
  3.      */   
  4.     @SuppressWarnings("rawtypes")  
  5.     private String getParameterMap(HttpServletRequest request) {  
  6.         Map map = request.getParameterMap();  
  7.         String text = "";  
  8.         if (map != null) {  
  9.             Set set = map.entrySet();  
  10.             Iterator iterator = set.iterator();  
  11.             while (iterator.hasNext()) {  
  12.                 Map.Entry entry = (Entry) iterator.next();  
  13.                 if (entry.getValue() instanceof String[]) {  
  14.                     logger.info("==A==entry的key: " + entry.getKey());  
  15.                     String key = (String) entry.getKey();  
  16.                     if (key != null && !"id".equals(key) && key.startsWith("[") && key.endsWith("]")) {  
  17.                         text = (String) entry.getKey();  
  18.                         break;  
  19.                     }  
  20.                     String[] values = (String[]) entry.getValue();  
  21.                     for (int i = 0; i < values.length; i++) {  
  22.                         logger.info("==B==entry的value: " + values[i]);  
  23.                         key += "="+values[i];  
  24.                     }  
  25.                     if (key.startsWith("[") && key.endsWith("]")) {  
  26.                         text = (String) entry.getKey();  
  27.                         break;  
  28.                     }  
  29.                 } else if (entry.getValue() instanceof String) {  
  30.                     logger.info("==========entry的key: " + entry.getKey());  
  31.                     logger.info("==========entry的value: " + entry.getValue());  
  32.                 }  
  33.             }  
  34.         }  
  35.         return text;  
  36.     }  


方式三:通过获取所有参数名的方式

这种方式也存在弊端  对json串中不能传特殊字符,比如/=, =, /, ~等的这样的符号都不能有如果存在也不会读出来,他的模式和Map的方式是差不多的,也是转成Map处理的

  1. /**  
  2.      * 方法说明 :通过获取所有参数名的方式 
  3.      */   
  4.     @SuppressWarnings({ "rawtypes", "unchecked" })  
  5.     private String getParamNames(HttpServletRequest request) {    
  6.         Map map = new HashMap();    
  7.         Enumeration paramNames = request.getParameterNames();    
  8.         while (paramNames.hasMoreElements()) {    
  9.             String paramName = (String) paramNames.nextElement();    
  10.     
  11.             String[] paramValues = request.getParameterValues(paramName);    
  12.             if (paramValues.length == 1) {    
  13.                 String paramValue = paramValues[0];    
  14.                 if (paramValue.length() != 0) {    
  15.                     map.put(paramName, paramValue);    
  16.                 }    
  17.             }    
  18.         }    
  19.     
  20.         Set<Map.Entry<String, String>> set = map.entrySet();    
  21.         String text = "";  
  22.         for (Map.Entry entry : set) {    
  23.             logger.info(entry.getKey() + ":" + entry.getValue());    
  24.             text += entry.getKey() + ":" + entry.getValue();  
  25.             logger.info("text------->"+text);  
  26.         }    
  27.         if(text.startsWith("[") && text.endsWith("]")){  
  28.             return text;  
  29.         }  
  30.         return "";  
  31.     }  


附上一点常用的Content-type的方式

application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 application/json;charset=utf-8 -> json数据


最后附上发送方式的连接

http://www.cnblogs.com/SimonHu1993/p/7295765.html

原文地址:https://www.cnblogs.com/SimonHu1993/p/7295750.html