缺少请求正文的Spring Boot POST请求?

时间:2018-02-08 08:29:36

标签: java spring spring-mvc spring-boot

我有一个非常简单的HTML表单页面(它是src / main / resources / public / web.html中Spring Boot Web应用程序的一部分),用于将字符串从textarea发布到Spring Boot Web应用程序版本1.5。 2。

<form action="" method="post">
<textarea cols="128" rows="40" name="query"></textarea>
<input value="Send" type="submit">
</form>

用于处理POST请求的SpringBoot类:

@RestController
public class QueryController {
    @RequestMapping(value = "/handle", method = RequestMethod.POST)
    protected void handlePost(@RequestBody String postBody) throws Exception {
       // Get query from postBody here
    }
}

它适用于客户端textarea中的小字符串。但是,当String很大时(例如:使用HTTP请求标头:Content-Length:3789333(3 MB))。 Spring Boot会抛出这样的异常:

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: protected void QueryController.handlePost(java.lang.String) throws java.lang.Exception
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:154)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)

我不确定导致此问题的原因,我正在使用Spring Boot中嵌入式Tomcat运行Web应用程序。

3 个答案:

答案 0 :(得分:1)

我不确定,但这可能是因为错过了内容的编码?

答案 1 :(得分:1)

问题是@RequestBody无法获取大查询的值。但是,从HttpServletRequest获取请求体可以获得值

 protected void handlePost(HttpServletRequest httpServletRequest) throws Exception {
    String postBody = this.getPOSTRequestBody(httpServletRequest); 

 }

答案 2 :(得分:0)

将您的控制器更新为以下内容:

@RestController
public class QueryController {
    @RequestMapping(value = "/handle", method = RequestMethod.POST)
    protected void handlePost(@RequestParam(value="query",required=false) String query) throws Exception {
       // Your code goes here
    }
}

如果你没有通过参数,你将获得org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'query' is not present。如果不需要参数,则可以将required=false添加到RequestParam。对于RequestParam,默认为required=true

这取决于您的服务器。我希望您使用Tomcat。默认情况下,服务器具有maxPostSize。以下是针对Tomcat的

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
               maxPostSize="6291456" />
我之前的代码中

maxPostSize为6MB。

相关问题