java spring boot RestTemplate 请求中文乱码 中文变?

转自:https://blog.csdn.net/qq_32193151/article/details/72902898

restTemplate作为spring web client下的一个工具类 对http请求做了一层封装,用起来也更加简洁容易,但最近遇到一个问题就是在发送请求时由于请求中包含中文导致乱码,都变成???????一堆问号

解决方案: 

@Bean配置方法:

@Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        return restTemplate;
    }

 

applicationContext.xml配置方法:




    
    
        
        
    

    
        
        
            
                
                
                
                
                    
                        
                            text/plain;charset=UTF-8
                        
                    
                
            
        
    

然后在使用的地方自动注入就好啦~~

再看看为什么会乱码:

public RestTemplate() {
        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (romePresent) {
            this.messageConverters.add(new AtomFeedHttpMessageConverter());
            this.messageConverters.add(new RssChannelHttpMessageConverter());
        }
        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (jacksonPresent) {
            this.messageConverters.add(new MappingJacksonHttpMessageConverter());
        }
    }

从RestTemplate 构造方法可以看出restTemplate默认的messageConverters有好几个,这次的主角是StringHttpMessageConverter:

public class StringHttpMessageConverter extends AbstractHttpMessageConverter {

    public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

    private final Charset defaultCharset;

    private final List availableCharsets;

    private boolean writeAcceptCharset = true;


    /**
     * A default constructor that uses {@code "ISO-8859-1"} as the default charset.
     * @see #StringHttpMessageConverter(Charset)
     */
    public StringHttpMessageConverter() {
        this(DEFAULT_CHARSET);
    }

    /**
     * A constructor accepting a default charset to use if the requested content
     * type does not specify one.
     */
    public StringHttpMessageConverter(Charset defaultCharset) {
        super(new MediaType("text", "plain", defaultCharset), MediaType.ALL);
        this.defaultCharset = defaultCharset;
        this.availableCharsets = new ArrayList(Charset.availableCharsets().values());
    }

    /**
     * Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
     * 

Default is {@code true}. */ public void setWriteAcceptCharset(boolean writeAcceptCharset) { this.writeAcceptCharset = writeAcceptCharset; } @Override public boolean supports(Class clazz) { return String.class.equals(clazz); } @Override protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException { Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType()); return StreamUtils.copyToString(inputMessage.getBody(), charset); } @Override protected Long getContentLength(String s, MediaType contentType) { Charset charset = getContentTypeCharset(contentType); try { return (long) s.getBytes(charset.name()).length; } catch (UnsupportedEncodingException ex) { // should not occur throw new IllegalStateException(ex); } } @Override protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException { if (this.writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); StreamUtils.copy(s, charset, outputMessage.getBody()); } /** * Return the list of supported {@link Charset}. *

By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses. * @return the list of accepted charsets */ protected List getAcceptedCharsets() { return this.availableCharsets; } private Charset getContentTypeCharset(MediaType contentType) { if (contentType != null && contentType.getCharSet() != null) { return contentType.getCharSet(); } else { return this.defaultCharset; } } }

可以看到StringHttpMessageConverter默认是ISO-8859-1编码(有空可以看下别的MessageConverter其实都是UTF-8的),所以就把它改了就好啦~

你可能感兴趣的:(java)