跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • mockMvcResponse,中文乱码
未分類
5 2 月 2021

mockMvcResponse,中文乱码

mockMvcResponse,中文乱码

資深大佬 : beichenhpy 1

代码如下

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": "允许进入" } 

不知道怎么办了。。求助

大佬有話說 (3)

  • 主 資深大佬 : beichenhpy

    我自己解决了,果然被降权的我没人回答
    https://stackoverflow.com/questions/58525387/mockmvc-no-longer-handles-utf-8-characters-with-spring-boot-2-2-0-release

  • 資深大佬 : Jrue0011

    我是直接参考 MockMvcResultHandlers.PrintWriterPrintingResultHandler 写了一个直接指定 Charset 的 PrintingResultHandler 子类然后在测试里用,而不用 MockMvcResultHandlers.print()…

    https://paste.ubuntu.com/p/dmsjmqWm5W/

  • 資深大佬 : Jrue0011

    不过 MockHttpServletRequest 和 MockHttpServletResponse 设置 CharacterEncoding 的时候会更新 ContentType…
    所以如果有调用 andExpect 对比 ContentType 的话,比如

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

    得放在 andDo 前面…

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具