All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ksyun.api.sdk.http.RestTemplateConfiguration Maven / Gradle / Ivy

There is a newer version: 2.1.8
Show newest version
package com.ksyun.api.sdk.http;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PlaceholderConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Component
public class RestTemplateConfiguration {
	@Autowired(required = false)
	private ClientHttpRequestFactoryConfig clientHttpRequestFactoryConfig;

	// PropertyPlaceholderHelper
	@Bean
	public PropertyPlaceholderHelper createPropertyPlaceholderHelper() {
		return new PropertyPlaceholderHelper(
				PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX,
				PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX);
	}

	// RestTemplate
	// only support json converter
	@Bean
	public RestTemplate createRestTemplate() {
		List> message_converters = new ArrayList>();
		message_converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		message_converters.add(new FormHttpMessageConverter());
		// jacson
		Gson gson = new GsonBuilder().serializeNulls()
				.excludeFieldsWithoutExposeAnnotation().create();
		GsonHttpMessageConverter gmc = new GsonHttpMessageConverter();
		gmc.setGson(gson);
		message_converters.add(gmc);
		RestTemplate rest = new RestTemplate(message_converters);
		if(clientHttpRequestFactoryConfig!=null){
			ClientHttpRequestFactoryUtils.init(clientHttpRequestFactoryConfig);
		}
		ClientHttpRequestFactory factory=ClientHttpRequestFactoryUtils.getHttpComponentsClientHttpRequestFactory();
		rest.setRequestFactory(factory);
		rest.setErrorHandler(new DefaultResponseErrorHandler());
		return rest;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy