RequestBody not accepted for RequestMethod.DELETE

2019-09-14 10:36发布

问题:

I'm using tomcat v8 and trying to post a object thru RequestBody to my REST API. This REST API is basically RequestMethod.DELETE as the logic inside this API is to delete the object that was passed in the RequestBody.

This didn't work for me. I had to later convert my method to POST but I am still wondering does DELETE doesn't accept RequestBody ?

Is this the restriction from the Spring framework or REST principles or something to do with my Tomcat configuration (server.xml) file.

回答1:

but I am still wondering does DELETE doesn't accept RequestBody ?

This is expected behavior. The RFC 7231 version of the HTTP 1.1 specification states:

A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.

In this case, you appear to have run into default restrictions in Tomcat. (This is entirely legitimate behavior ... according to the HTTP spec.)

You could override the default behavior: see the other answer. However, it strikes me as poor API design for a DELETE verb to allow or require a request body. Certainly it is counter-intuitive.



回答2:

Is this the restriction from the Spring framework or REST principles or something to do with my Tomcat configuration (server.xml) file

Yes you have something to do with your Tomcat configuration.

You have to enable parsing DELETE methods (same goes for PUT) in server.xml as follows:

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               parseBodyMethods="POST,PUT,DELETE"
               redirectPort="8443" />