Search code examples
spring-bootinputstream

How override InputStream in SpringBoot before controller?


How I can override @RequestBody content in spring boot before it reaches to the controller?

  1. I know that there is WebMvcConfigurer and HandlerInterceptorAdapter classes to handle request before controller.

  2. Also I've googled for RequestBodyAdviceAdapter as well.

There are several links that didn't work for spring boot.

How to read request.getInputStream() multiple times

How to modify request body before reaching controller in spring boot

Now can I read input stream into string, make some modification and set back into input stream for the controller?


Solution

  • Solution 1: (In my opinion better solution) As suggested in comment try using the @JsonProperty or custom De-/Serializer for the object.

    Solution 2: Add a @ControllerAdvice and implement RequestBodyAdvice and override the beforeBodyRead as

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        InputStream body = inputMessage.getBody();
        String bodyStr = IOUtils.toString(body, Charset.forName("UTF-8"));
        /*
        Update bodyStr as you wish
        */
        HttpInputMessage ret = new MappingJacksonInputMessage(new ByteArrayInputStream(bodyStr.getBytes()), inputMessage.getHeaders()); //set the updated bodyStr
        return ret;
    }