简单描述
测试代码,发起一个返回中文的json,发现在谷歌和postman中显示正常,而在火狐以及httpclient中中文乱码。
问题所在
查看springboot源码,已经自动注入CharacterEncodingFilter
public class HttpEncodingAutoConfiguration {
private final HttpEncodingProperties properties;
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean(CharacterEncodingFilter.class)
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
return filter;
}
...
}
debug到此处,发现得到的encoding确实为UTF-8,但是forceRequestEncoding和forceResponseEncoding都是为false的。
而在CharacterEncodingFilter代码
if (encoding != null) {
if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
}
if (isForceResponseEncoding()) {
response.setCharacterEncoding(encoding);
}
}
检查发现,springboot有一个参数spring.http.encoding.force 默认为false,导致forceRequestEncoding和forceResponseEncoding都为false。
解决方案
在application.yml中添加参数
spring.http.encoding.force: true