Java如何从HttpServletRequest中读取HTTP请求的body

注意:下面方法已验证通过。

HTTP请求中的是字符串数据:

//字符串读取

void charReader(HttpServletRequest request) {

BufferedReader br = request.getReader();

String str, wholeStr = "";
while((str = br.readLine()) != null){
wholeStr += str;
}

System.out.println(wholeStr);

}

//二进制读取

void binaryReader(HttpServletRequest request) {

int len = request.getContentLength();
ServletInputStream iii = request.getInputStream();
byte[] buffer = new byte[len];
iii.read(buffer, 0, len);

}

注意:

request.getInputStream(); request.getReader();和request.getParameter("key");这三个函数中任何一个函数执行一次后(可正常读取body数据),之后再执行就无效了。

你可能感兴趣的:(JAVA,Servlet)