Alternative of @RequestBody

2019-07-26 05:50发布

问题:

Is there an alternative way to obtain a reference to a request's body without using the approach with the annotation? I'm using GAE + Spring and everytime I use @RequestBody in the signatures of my controller methods, the server returns 415 Unsupported Media Type. All I'm trying to do is read a JSON encoded message on a Post method. Thanks.

回答1:

You can take in a parameter of HttpServletRequest, and read the ServletInputStream using getInputStream() from there. The stream will contain the body of the request.

@Controller
public class MyController {
    @RequestMapping("/test")
    public String aTest(HttpServletRequest request) {
        InputStream body = request.getInputStream();
        //process request body
        return myReturnVal;
    }
}


回答2:

Try this, on the RequestMapping configure the headers to accept application/json and be sure to configure a jackson message convertor for this type