简体   繁体   中英

I am using the Interceptor in springboot , but there I am getting the error as

I have to use the interceptor in springboot to to do some processing before & after request gets proceed. But while using it I am getting one error: As of now I just tried to use to pre-handle method and there I am facing this issue.

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing"
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:160)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:131)

I thought there might be some problem in Json conversion so I tried other solutions like Jackson library there also I am facing the same issue.

Here I have to convert the HttpServletRequest to jsonObject but i am getting the mentioned error. When I removed the below logic of BufferedReader to jsonObject conversion and just return true from prehandle method it works properly.

Code:

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);

            JSONObject obj = new JSONObject(jb.toString());
            System.out.println(obj);
        } catch (Exception e) {
        }

        return super.preHandle(request, response, handler);
    }

I am getting 400 while testing the above call from postman.

When you read a body from the HttpServletRequest the body is consumed so when it reaches the controller , where you might have mentioned @RequestBody , there will be no data to be received. That's why you are receiving Status Code : 400 Required request body is missing .

In simpler terms body in the request can be read only once.

But If you want to process before the business logic you have to cache that in the interceptor for using it (May be using ThreadLocal) or look into RequestBodyAdviceAdapter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM