读取方式一:通过BufferedReader,实例如下:
/**
* 获取POST请求中Body参数-方式一字符串的方式接收
* @param request
* @return 字符串
*/
public String getParm(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
String line = null;
try {
//接收request数据流,并指定编码格式接收
br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
方式二:IOUtils的方式
/**
* 获取POST请求中Body参数-方式一 二进制数组的方式接收
* @param request
* @return 字符串
*/
public byte[] getParm2(HttpServletRequest request) {
byte[] bytes = new byte[0];
try {
bytes = IOUtils.toByteArray(request.getInputStream());
} catch (IOException e) {
// TODO 异常处理可具体处理
e.printStackTrace();
}
return bytes;
}
/**
* 获取POST请求中Body参数-方式一 二进制数组的方式接收,然后转换成字符串
* @param request
* @return 字符串
*/
public String getParm3(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
String line = null;
byte[] bytes = new byte[0];
try {
bytes = IOUtils.toByteArray(request.getInputStream());
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ServletInputStream servletInputStream = new DelegatingServletInputStream(byteArrayInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(servletInputStream));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO 异常处理可具体处理
e.printStackTrace();
}
return sb.toString();
}
说明:也可以对应JSON对象的转换,如下
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
AccountVo accountVo1 = jsonObject.toJavaObject(AccountVo.class);
AccountVo accountVo = JSONObject.parseObject(sb.toString(), AccountVo.class);
注意:
获取body参数,需要在request.getParameter()方法之前调用(如果有需要取QueryString参数的话),因为一旦调用了getParameter()方法之后,再通过IO流的方式获取body参数就失效了,会返回“”
IOUtils的详细了解可参考大牛博客:
IOUtils总结