java 获取request中的请求参数
1、get 和 post请求方式
(1)request.getParameterNames(); 获取所有参数key后。遍历request.getParameter(key)获取value
(2)request.getParameterMap() 。直接包含参数key和value值,简单方便
Map<String, String[]>maps = request.getParameterMap();
for (Map.Entry<String, String[]> entry : maps.entrySet()) { String cs = entry.getKey() + ":"+Arrays.toString(entry.getValue())+";"; }
2、获取请求类型为request payload方式
这里就不介绍文件流的了,主要针对 后端采用@RequestBody方式的请求
这类数据通过以上2种方式是获取不到的,它是存放在流里面,要通过getInputStream()或getReader()方式获取
public String getRequestData(HttpServletRequest httpServletRequest){ HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(httpServletRequest); StringBuilder sb = new StringBuilder(); BufferedReader reader = null; InputStreamReader inputStreamReader=null; ServletInputStream servletInputStream =null; try { servletInputStream = httpServletRequestWrapper.getInputStream(); inputStreamReader=new InputStreamReader (servletInputStream, Charset.forName("UTF-8")); reader = new BufferedReader(inputStreamReader); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { return ""; }finally { try { if(servletInputStream!=null){ servletInputStream.close(); } if(inputStreamReader!=null){ inputStreamReader.close(); } if(reader!=null){ reader.close(); } } catch (IOException e) { } } return sb.toString (); }
需要注意的是getInputStream()这种获取流的方式 只能用一次,如果多次调用 需要缓存起来,不然流的数据到不了Controller层,报400错误
版权声明:如需转载,请注明!PS:如是转载随便,请忽略