HttpServletRequest中读取HTTP请求的body
程序员文章站
2024-02-04 20:01:40
...
背景
Spring MVC 等框架用久了之后,发现对于POST请求里面如果不使用@RequestBody 好像很难获得POST的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);
}
@RequestBody
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
@ResponseBody
public ServiceResult feedbackEmail(HttpServletRequest request,
@RequestBody JSONObject jsonObject
){
String emailTitle = jsonObject.get("emailTitle").toString();
String emailBody = jsonObject.get("emailBody").toString();
}
@RequestBody 可以使用JSONObject, Map ,或者ObjectDTO绑定body。
或者使用
@RequestParam
@RequestMapping(value = "/email", method = RequestMethod.POST)
@ResponseBody
public ServiceResult Email(HttpServletRequest request,
@RequestParam("emailTitle")String emailTitle,
@RequestParam("emailBody")String emailBody) {
BufferedReader br = request.getReader();
while((str1 = br.readLine()) != null) {
wholeStr += str1;
}
注意
request.getInputStream(); request.getReader();和request.getParameter(“key”);这三个函数中任何一个函数执行一次后(可正常读取body数据),之后再执行就无效了。
参考:
http://blog.csdn.net/zxygww/article/details/47045055(body数据读取)
http://blog.csdn.net/xkhgnc_6666/article/details/51767838(post请求中参数为json格式)
推荐阅读
-
获取HttpServletRequest请求Body中的内容
-
HttpServletRequest中读取HTTP请求的body
-
SpringBoot中获取请求的Json格式并解决request的请求流只能读取一次的问题
-
PHP中模拟处理HTTP PUT请求的例子_php实例
-
springMVC拦截器从Request中获取Json格式并解决request的请求流只能读取一次的问题
-
SpringBoot 之 SpringMVC拦截器从Request中获取参数并解决request的请求流只能读取一次的问题
-
php模拟asp中的XmlHttpRequest实现http请求的代码_PHP
-
android实现http中请求访问添加cookie的方法
-
android实现http中请求访问添加cookie的方法
-
Node.js中的http请求客户端示例(request client)