Spring REST service: retrieving JSON from Request

后端 未结 11 654
甜味超标
甜味超标 2020-11-27 04:35

I am building a REST service on Spring 3.1. I am using @EnableWebMVC annotation for that. Since my service will only be accepting JSON requests, I would also like to dump th

11条回答
  •  萌比男神i
    2020-11-27 04:45

    For getting data from Body you can try to read and recreate InputStream in RequestBodyAdviceAdapter:

    @ControllerAdvice
    public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
    
        @Override
        public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException {
            String body = IOUtils.toString(inputMessage.getBody(), UTF_8.name());
    
            HttpInputMessage myMessage = new HttpInputMessage(){
                @Override
                public InputStream getBody() throws IOException {
                    return new ByteArrayInputStream(body.getBytes());
                }
                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
    
            System.out.println("Data from Body: " + body);
    
            return super.beforeBodyRead(myMessage, parameter, targetType, converterType);
        }
    
        @Override
        public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) {
            System.out.println("Data from Body is empty");
            return super.handleEmptyBody(body, inputMessage, parameter, targetType, converterType);
        }
    
        @Override
        public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) {
            return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
        }
    
        @Override
        public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) {
            return true;
        }
    }
    

提交回复
热议问题