RestTemplate StringHttpMessageConverter 中文乱码
程序员文章站
2022-06-26 23:29:35
...
解决方案
版本:org.springframework.boot:spring-boot-starter-web:2.1.6.RELEASE
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
RestTemplate restTemplate = restTemplateBuilder.build();
restTemplate.getMessageConverters().forEach(httpMessageConverter -> {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
}
});
return restTemplate;
}
问题原因
版本:org.springframework:spring-web:5.1.8.RELEASE
org.springframework.web.client.RestTemplate
import org.springframework.http.converter.StringHttpMessageConverter;
/**
* Create a new instance of the {@link RestTemplate} using default settings.
* Default {@link HttpMessageConverter HttpMessageConverters} are initialized.
*/
public RestTemplate() {
{...}
this.messageConverters.add(new StringHttpMessageConverter());
{...}
}
org.springframework.http.converter.StringHttpMessageConverter
import java.nio.charset.StandardCharsets;
/**
* Thedefault charset used by the converter.
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;
/**
* A default constructor that uses {@code "ISO-8859-1"} as the default charset.
* @see #StringHttpMessageConverter(Charset)
*/
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
}
(完)
上一篇: CommonJS
下一篇: YII2.0多模块配置