package com.jpsoft.shinestar.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        //增加超时，避免耗时操作报错
        requestFactory.setConnectTimeout(20000);
        requestFactory.setReadTimeout(20000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
            if(httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
                break;
            }
        }

        return restTemplate;
    }
}
