如何在控制器之前重写SpringBoot中的InputStream?

gog*_*ubi 3 inputstream spring-boot

在 Spring Boot 到达控制器之前,如何覆盖 @RequestBody 内容?

  1. 我知道有WebMvcConfigurerHandlerInterceptorAdapter类在控制器之前处理请求。

  2. 我也用谷歌搜索了RequestBodyAdviceAdapter

有几个链接不适用于 Spring Boot。

如何多次读取 request.getInputStream()

如何在 Spring Boot 中到达控制器之前修改请求正文

现在我可以将输入流读入字符串,进行一些修改并设置回控制器的输入流吗?

Lip*_*ipu 7

解决方案 1:(在我看来更好的解决方案)正如评论中所建议的,尝试对对象使用 @JsonProperty 或自定义 De-/Serializer。

解决方案2:添加@ControllerAdvice并实现RequestBodyAdvice并覆盖beforeBodyRead为

@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;
}
Run Code Online (Sandbox Code Playgroud)