环境

  • springboot 2.2.6

  • junit5

  • @WebMvcTest

  • MockMvc

乱码问题

使用 MockMvc 执行 http 请求,得到的响应后,print(), 控制台中文乱码。

{"code":10001,"message":"请求方式不支持","data":"Request method 'POST' not supported","responseTime":"2022-05-27T14:19:45.806"}

原因

响应体中:

Headers = [Content-Type:"application/json;charset=ISO-8859-1"]

源码位置 MockHttpServletResponse#characterEncoding

// ISO-8859-1
@Nullable
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;

我也不知道为什么要设置成默认这个编码。

解决办法

方式一:将请求后得到的response,修改其编码值

mockMvc.perform(post("/xxx")).andReturn().getResponse().setCharacterEncoding(WebUtils.DEFAULT_CHARACTER_ENCODING);

缺点:每次都要调用处理,麻烦。

方式二:全局拦截 (推荐)

创建mockMvc,增加filter。

    private MockMvc mockMvc;
    @BeforeEach
    void before(WebApplicationContext context) {
        mockMvc = MockMvcBuilders.webAppContextSetup(context)
                .addFilter((request, response, chain) -> {
                    response.setCharacterEncoding("UTF-8");
                    chain.doFilter(request, response);
                }, "/*")
                .build();
    }