Java Code Examples for org.springframework.web.client.RestTemplate#getMessageConverters()

The following examples show how to use org.springframework.web.client.RestTemplate#getMessageConverters() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SmartRestTemplateConfig.java    From smart-admin with MIT License 6 votes vote down vote up
/**
 * fastJsonRestTemplate
 *
 * @return
 */
@Bean(name = "fastJsonRestTemplate")
public RestTemplate fastJsonRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory());

    HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));

    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.add(1,converter);
    converters.add(fastConverter);
    return restTemplate;
}
 
Example 2
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    xmlMapper.registerModule(new JsonNullableModule());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            ThreeTenModule module = new ThreeTenModule();
            module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
            module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
            module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
            mapper.registerModule(module);
            mapper.registerModule(new JsonNullableModule());
        }
    }
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
Example 3
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            ThreeTenModule module = new ThreeTenModule();
            module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
            module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
            module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
            mapper.registerModule(module);
            mapper.registerModule(new JsonNullableModule());
        }
    }
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
Example 4
Source File: RestTemplateConfiguration.java    From seed with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate(){
    RestTemplate restTemplate = new RestTemplate(this.createFactory());
    //解决中文乱码问题
    //由于RestTemplate.postForObject()使用的StringHttpMessageConverter默认编码是ISO-8859-1,所以中文会乱码
    //所以我们要移除默认的StringHttpMessageConverter,再添加新的由UTF-8编码的StringHttpMessageConverter
    List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
    HttpMessageConverter<?> converterTarget = null;
    for(HttpMessageConverter<?> item : converterList){
        if(StringHttpMessageConverter.class == item.getClass()){
            converterTarget = item;
            break;
        }
    }
    if(null != converterTarget){
        converterList.remove(converterTarget);
    }
    converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    //由于converterList是restTemplate对象的全局变量的引用
    //所以不用restTemplate.setMessageConverters(converterList);
    return restTemplate;
}
 
Example 5
Source File: DCTMJacksonClient.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void initRestTemplate(RestTemplate restTemplate) {
    super.initRestTemplate(restTemplate);
    restTemplate.setErrorHandler(new DCTMJacksonErrorHandler(restTemplate.getMessageConverters()));
    for(HttpMessageConverter<?> c : restTemplate.getMessageConverters()) {
        if(c instanceof MappingJackson2HttpMessageConverter) {
            ((MappingJackson2HttpMessageConverter)c).getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        } else if(c instanceof FormHttpMessageConverter) {
            try {
                Field pcField = FormHttpMessageConverter.class.getDeclaredField("partConverters");
                pcField.setAccessible(true);
                List<HttpMessageConverter<?>> partConverters = ((List<HttpMessageConverter<?>>)pcField.get(c));
                for(HttpMessageConverter<?> pc : partConverters) {
                    if(pc instanceof MappingJackson2HttpMessageConverter) {
                        ((MappingJackson2HttpMessageConverter)pc).getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                        break;
                    }
                }
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
 
Example 6
Source File: RestTemplateFactory.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
                                                           int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
    HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(maxConnPerRoute)
            .setMaxConnTotal(maxConnTotal)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
            .build();
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    //set jackson mapper
    for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            ObjectMapper objectMapper = createObjectMapper();
            MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
            mj2hmc.setObjectMapper(objectMapper);
        }
    }

    return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
            new Class[]{RestOperations.class},
            new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
 
Example 7
Source File: DataflowTemplateTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private void assertCorrectMixins(RestTemplate restTemplate) {
	boolean containsMappingJackson2HttpMessageConverter = false;

	for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
		if (converter instanceof MappingJackson2HttpMessageConverter) {
			containsMappingJackson2HttpMessageConverter = true;

			final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
			assertCorrectMixins(jacksonConverter.getObjectMapper());
		}
	}

	if (!containsMappingJackson2HttpMessageConverter) {
		fail("Expected that the restTemplate's list of Message Converters contained a "
				+ "MappingJackson2HttpMessageConverter");
	}
}
 
Example 8
Source File: DefaultWidgetMarketplaceService.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
/**
 * Create a JSON REST Template for requests
 * @return a RestTemplate configured to process JSON data
 */
private RestTemplate getRestJsonTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
    // Add JSON message handler
    MappingJackson2HttpMessageConverter json = new MappingJackson2HttpMessageConverter();
    List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
    supportedMediaTypes.add(new MediaType("application","json", Charset.forName("UTF-8")));
    // Add default media type in case marketplace uses incorrect MIME type, otherwise
    // Spring refuses to process it, even if its valid JSON
    supportedMediaTypes.add(new MediaType("application","octet-stream", Charset.forName("UTF-8")));
    json.setSupportedMediaTypes(supportedMediaTypes);
    mc.add(json);
    restTemplate.setMessageConverters(mc);
    return restTemplate;
}
 
Example 9
Source File: ApiClient.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            ThreeTenModule module = new ThreeTenModule();
            module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
            module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
            module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
            mapper.registerModule(module);
            mapper.registerModule(new JsonNullableModule());
        }
    }
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
Example 10
Source File: SpringRESTClientConnector.java    From egeria with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor
 */
public SpringRESTClientConnector() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
    super();

    /*
     * Rather than creating a RestTemplate directly, the RestTemplateBuilder is used so that the
     * uriTemplateHandler can be specified. The URI encoding is set to VALUES_ONLY so that the
     * '+' character, which is used in queryParameters conveying searchCriteria, which can be a
     * regex, is encoded as '+' and not converted to a space character.
     * Prior to this change a regex containing a '+' character would be split into two space
     * separated words. For example, the regex "name_0+7" (which would match name_07, name_007,
     * name_0007, etc) would be sent to the server as "name_0 7".
     */
    DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
    builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);


    /* TODO: Disable SSL cert verification -- for now */
    HttpsURLConnection.setDefaultHostnameVerifier(bypassVerifier);
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, INSECURE_MANAGER, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    restTemplate = new RestTemplate();

    restTemplate.setUriTemplateHandler(builderFactory);

    /* Ensure that the REST template always uses UTF-8 */
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter);
    converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

}
 
Example 11
Source File: SkipperClientConfiguration.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
public RestTemplate validateRestTemplate(RestTemplate restTemplate) {
	boolean containsMappingJackson2HttpMessageConverter = false;

	for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
		if (converter instanceof MappingJackson2HttpMessageConverter) {
			containsMappingJackson2HttpMessageConverter = true;
		}
	}

	if (!containsMappingJackson2HttpMessageConverter) {
		throw new IllegalArgumentException(
				"The RestTemplate does not contain a required " + "MappingJackson2HttpMessageConverter.");
	}
	return restTemplate;
}
 
Example 12
Source File: AviRestUtils.java    From sdk with Apache License 2.0 5 votes vote down vote up
private static List<HttpMessageConverter<?>> getMessageConverters(RestTemplate restTemplate) {
    // Get existing message converters
    List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
    messageConverters.clear();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MappingJackson2HttpMessageConverter mycov = new MappingJackson2HttpMessageConverter(objectMapper);
    mycov.setPrettyPrint(true);
    messageConverters.add(mycov);
    return messageConverters;
}
 
Example 13
Source File: AuthenticatedRestTemplate.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a customized {@link MappingJackson2HttpMessageConverter} to process
 * payload from TMS Rest API.
 *
 * @return
 */
protected void makeRestTemplateWithCustomObjectMapper(RestTemplate restTemplate) {
    logger.debug("Getting new rest template");

    for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
        if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {
            MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = (MappingJackson2HttpMessageConverter) httpMessageConverter;

            // Bug with application/x-spring-data-compact+json: https://jira.spring.io/browse/DATAREST-404
            logger.debug("Setting supported media type to just JSON. The Accept header will be updated accordingly to application/json");
            mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));

            // This helps with joda deserialize of joda date time string
            logger.debug("Creating custom jackson2 objectmapper with serialization inclusion changes");
            Jackson2ObjectMapperFactoryBean jackson2ObjectMapperFactoryBean = new Jackson2ObjectMapperFactoryBean();
            jackson2ObjectMapperFactoryBean.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            jackson2ObjectMapperFactoryBean.afterPropertiesSet();

            ObjectMapper objectMapper = jackson2ObjectMapperFactoryBean.getObject();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        }

        // The default encoding is set to ISO-8559-1 for String type, which is why we have to override it here
        // For more info: https://jira.spring.io/browse/SPR-9099
        //TODO investigate but this should probalby replaced with setting the right header: headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        if (httpMessageConverter instanceof StringHttpMessageConverter) {
            StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) httpMessageConverter;
            stringHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                            MediaType.parseMediaType("text/plain;charset=UTF-8"),
                            MediaType.ALL)
            );
        }
    }
}
 
Example 14
Source File: ProxyExchange.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public ProxyExchange(RestTemplate rest, NativeWebRequest webRequest,
		ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
		Type type) {
	this.responseType = type;
	this.rest = rest;
	this.webRequest = webRequest;
	this.mavContainer = mavContainer;
	this.binderFactory = binderFactory;
	this.delegate = new RequestResponseBodyMethodProcessor(
			rest.getMessageConverters());
}
 
Example 15
Source File: DCTMJaxbClient.java    From documentum-rest-client-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void initRestTemplate(RestTemplate restTemplate) {
    super.initRestTemplate(restTemplate);
    restTemplate.setErrorHandler(new DCTMJaxbErrorHandler(restTemplate.getMessageConverters()));
    for(HttpMessageConverter<?> c : restTemplate.getMessageConverters()) {
        if(c instanceof FormHttpMessageConverter) {
            ((FormHttpMessageConverter)c).addPartConverter(new Jaxb2RootElementHttpMessageConverter());
            break;
        }
    }
}