mockMvcResponse,中文乱码

2021-02-03 11:13:19 +08:00
 uselessVisitor

代码如下

mockMvc
                .perform(MockMvcRequestBuilders
                        .post("/mock/post")
                        .content(JSON.toJSONString(person1))
                        .contentType(MediaType.APPLICATION_JSON)
                        .header("X-Access-token", "1"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn().getResponse().setCharacterEncoding("UTF-8");

设置了 utf-8 了,idea 控制台打印结果

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"code":200,"result":"允许进入"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

使用 HTTP-CLIENT 返回正常

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 03 Feb 2021 03:13:42 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "code": 200,
  "result": "允许进入"
}

不知道怎么办了。。求助

1413 次点击
所在节点    Java
3 条回复
uselessVisitor
2021-02-03 11:34:10 +08:00
Jrue0011
2021-02-04 10:04:07 +08:00
我是直接参考 MockMvcResultHandlers.PrintWriterPrintingResultHandler 写了一个直接指定 Charset 的 PrintingResultHandler 子类然后在测试里用,而不用 MockMvcResultHandlers.print()...

https://paste.ubuntu.com/p/dmsjmqWm5W/
Jrue0011
2021-02-04 10:16:56 +08:00
不过 MockHttpServletRequest 和 MockHttpServletResponse 设置 CharacterEncoding 的时候会更新 ContentType...
所以如果有调用 andExpect 对比 ContentType 的话,比如

andExpect(content().contentType(MediaType.APPLICATION_JSON))

得放在 andDo 前面...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/750851

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX