Spring's @RequestBody providing empty string on POST

前端 未结 4 2167
自闭症患者
自闭症患者 2020-12-19 03:15

I have an application with Spring 3.0.5.RELEASE trying to get the full content of a post using @RequestBody. The method is called, but the string passed is always empty. I h

相关标签:
4条回答
  • 2020-12-19 03:38

    Had a similar problem - the string received by spring controller was always empty. Tinkered with my spring config but with no result. Finally the problem was that the client was actually was not sending anything body!(due to some typo of mine)

    If found with a similar error, its worth checking once if the client's payload is actually non-empty.

    0 讨论(0)
  • 2020-12-19 03:45

    How are you POSTing messages to this URL? Are you positive that the HTTP request contains what you think it does? I suggest removing any web browsers from the picture and drop down to something low-level like curl which lets you send any type of HTTP message yourself.

    0 讨论(0)
  • 2020-12-19 03:48

    Here is a code snippet of ServletServerHttpRequest, which extends HttpInputMessage. I am pretty positive this is the implementation that you are using in your code:

    public InputStream getBody() throws IOException {
        return this.servletRequest.getInputStream();
    }
    

    In other words, the request body is meant to be read as the input stream of the HttpServletRequest object.

    The request's input stream is not valid in several situations, but I can't find the correct documentation for it at the moment. For example, if you call request.getParameter() on a post request, tomcat has to read the input stream in order to interpret the parameters, thus afterwards when you read the input stream, it is empty because it has reached the end already.

    Perhaps you are invoking getParameter somewhere in an interceptor or perhaps a filter defined in web.xml. Another option is that Spring is doing that for you, for example, if your controller has some other method with complex @RequestMappings (such as reading param values, or header values).

    I have two suggestions for you:

    1. Add a servlet filter (before spring gets a chance to act), and wrap the request with your own wrapper (just extend HttpServletRequestWrapper). This way you can put breakpoints or log messages at some methods of the request object and see who's calling them.

    2. Use a pojo object parameter, and setup the bindings. It seems like a much cleaner way to read post data.

    0 讨论(0)
  • 2020-12-19 03:55

    Another reason that your XML may not be getting marshalled into your JAXB object is related to the namespaces in the XML.

    Versions of java after 1.8.101 are more strict about parsing namespaced XML. See JAXB doesn't unmarshall after updating java from 1.8.0_77 to 1.8.0_121

    In my case I was seeing a request body with all nulls and no exception being thrown to indicate that the XML parsing had failed.

    0 讨论(0)
提交回复
热议问题