概述
后端通过HttpServletRequest.getInputStream
获取消息体时,发现读取不出,代码如下:
@PostMapping("/test2")
public String test2(HttpServletRequest request) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String str=null;
while((str=reader.readLine())!=null){
System.out.println(str);
}
return "ok";
}
然后使用curl
命令发起请求:
$ curl -v --data "name=tom&password=123456" http://localhost:8080/test2
*
Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /test2 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Length: 24
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 24 out of 24 bytes
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 2
< Date: Wed, 05 Jun 2019 08:28:51 GMT
<
* Connection #0 to host localhost left intact
ok
然而后端无输出,这是因为Spring MVC检测到Content-Type: application/x-www-form-urlencoded
,已经先一步读取并解析了。因此后端可用下列方法读取:
@PostMapping("/test")
public String test(String name,String password) throws IOException {
System.out.println(name);
System.out.println(password);
return "ok";
}
如果非要使用HttpServletRequest.getInputStream
读取请求消息体呢?那就防止Spring MVC预先读取就行了,比如设置Content-Type: text/*
,代码如下所示:
$ curl -v --data "bbbbb" -H "Content-Type: text/*" http://localhost:8080/test2
*
Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /test2 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.58.0
> Accept: */*
> Content-Type: text/*
> Content-Length: 5
>
* upload completely sent off: 5 out of 5 bytes
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 2
< Date: Wed, 05 Jun 2019 08:31:28 GMT
<
* Connection #0 to host localhost left intact
ok
此时后端能够正确打印bbbb
了。
最后
以上就是喜悦黄豆为你收集整理的Spring MVC中获取不到请求消息体的全部内容,希望文章能够帮你解决Spring MVC中获取不到请求消息体所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复