V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
uselessVisitor
V2EX  ›  Java

mockMvcResponse,中文乱码

  •  
  •   uselessVisitor · 2021-02-03 11:13:19 +08:00 · 1401 次点击
    这是一个创建于 1170 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下

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

    不知道怎么办了。。求助

    uselessVisitor
        1
    uselessVisitor  
    OP
       2021-02-03 11:34:10 +08:00
    Jrue0011
        2
    Jrue0011  
       2021-02-04 10:04:07 +08:00
    我是直接参考 MockMvcResultHandlers.PrintWriterPrintingResultHandler 写了一个直接指定 Charset 的 PrintingResultHandler 子类然后在测试里用,而不用 MockMvcResultHandlers.print()...

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

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

    得放在 andDo 前面...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5476 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 03:09 · PVG 11:09 · LAX 20:09 · JFK 23:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.