如何使用Spring MVC Jackson拦截HttpServlet请求



我正在使用Spring/Jonson将json自动转换为POJO。所有操作都很好,除非我正在进行头部身份验证(使用过滤器)。我一直在使用request.getContentLength()来获取json字符串的长度。

这很好,直到json包含变音符号。其中内容长度报告为长一个字符。所以很明显,我必须得到实际的json主体。事实证明,这很困难,因为调用request.getInputStream会导致Jackson失败,因为输入流已经关闭。getReader也是如此。

所以,我做了如下博客中概述的:http://natch3z.blogspot.co.uk/2009/01/read-request-body-in-filter.html

它可以工作,但不能正确地编码为UTF-8。所以我换了这行:

  bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

至:

  bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

它在我的日志中显示了正确的json,但当jackson试图转换为pojo:时,我收到了这个错误

 nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0x9f 

我不知道该怎么做,如果有人有什么想法的话?

我刚刚发现:

我替换了这行:

final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());

这个:

final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes("UTF-8"));

我本应该早点意识到,但这可能会帮助其他有类似问题的人。

最新更新