第一步,约定传参编码格式

不管是使用httpclient,还是okhttp,都要设置传参的编码,为了统一,这里全部设置为utf-8

第二步,修改application.properties文件

增加如下配置:

spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

此时拦截器中返回的中文已经不乱码了,但是controller中返回的数据依旧乱码。

第三步,修改controller的@RequestMapping

修改如下:

produces="text/plain;charset=UTF-8"

 

 

这种方法的弊端是限定了数据类型,继续查找资料,在stackoverflow上发现解决办法,是在配置类中增加如下代码:

@Configuration
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }

    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}

便可以解决SpringBoot的中文乱码问题了。 

 

 


 

相关文章:

  • 2021-08-29
  • 2021-10-03
  • 2021-04-01
  • 2021-11-17
  • 2021-04-26
  • 2021-11-19
  • 2021-04-19
猜你喜欢
  • 2022-01-10
  • 2021-10-10
  • 2022-12-23
  • 2021-10-12
  • 2021-07-01
  • 2022-12-23
  • 2022-02-07
相关资源
相似解决方案