在spring MVC中如何获取请求体呢?
在spring MVC中如何获取请求要素呢?
通过如下方法:
/**
* Compatible with GET and POST
*
* @param request
* @return : <code>String</code>
* @throws IOException
*/
public static String getRequestQueryStr(HttpServletRequest request,
String charEncoding) throws IOException {
String submitMehtod = request.getMethod();
if (submitMehtod.equalsIgnoreCase("post")) {
byte[] bytes = getRequestPostBytes(request);
String charEncoding2 = request.getCharacterEncoding();// charset
System.out.println("[getRequestQueryStr]charEncoding:"
+ charEncoding2);
System.out.println("[getRequestQueryStr]Content-Type:"
+ request.getHeader(Constant2.REQUEST_HEADER_CONTENT_TYPE));
if(ValueWidget.isNullOrEmpty(charEncoding)){
charEncoding=SystemHWUtil.CHARSET_UTF;
}
return new String(bytes, charEncoding);
} else {// form method :Get
return request.getQueryString();
}
}
对GET请求的参数是没有问题的,但是对于POST请求获取不到为什么呢?
因为spring MVC已经获取了一遍request的stream,所以再次获取时是为空的,(这是输入流的特性,可以查查官网API),所以我获取到request 的InputStream之后调用reset,但是报错,不支持reset操作.
怎么办呢?
在spring MVC 的控制器中使用@RequestBody 注解,作用是获取请求体,格式是字节数组,见代码
@ResponseBody
@RequestMapping(value = "/jsonStub", produces = SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF)
public String json(Model model, HttpSession session,@RequestBody byte[]bytes,
HttpServletRequest request, String callback) throws IOException {
Map map=WebServletUtil.parseRequest(request, null);
if(ValueWidget.isNullOrEmpty(map)){
String postStr=new String(bytes,SystemHWUtil.CURR_ENCODING);//username=huangwei&password=123
System.out.println("postStr:"+postStr);//username=%E9%BB%84%E5%A8%81&password=123
postStr=URLDecoder.decode(postStr,SystemHWUtil.CURR_ENCODING);//{"username":"黄威","password":"123"}
map=WebServletUtil.parseRequestStr(postStr, true);
}
String content = HWUtils.getJsonP(map, callback);
return content;
}
@RequestBody后紧跟的参数将被注入请求体的字节数组(spring mVC帮我们完成的).
注意:request.getInputStream() 读取一次之后,再次读取就读取不到
上述代码依赖的方法:
/***
* Get request query string, form method : post
*
* @param request
* @return byte[]
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
/*当无请求参数时,request.getContentLength()返回-1 */
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
/***
* Get request query string, form method : post
*
* @param request
* @return
* @throws IOException
*/
public static String getRequestPostStr(HttpServletRequest request)
throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
参考:http://json20080301.iteye.com/blog/1874074?utm_source=tuicool