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

The following examples show how to use org.springframework.web.client.RestTemplate#setRequestFactory() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tutorials   File: ApiClient.java    License: 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 2
Source Project: openapi-generator   File: ApiClient.java    License: 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 Project: openapi-generator   File: ApiClient.java    License: 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
public static RestTemplate getRestTemplate() {// 手动添加
    SimpleClientHttpRequestFactory requestFactory=new SimpleClientHttpRequestFactory();
    requestFactory.setReadTimeout(120000);
    List<HttpMessageConverter<?>> messageConverters = new LinkedList<>();
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new SourceHttpMessageConverter<Source>());
    messageConverters.add(new AllEncompassingFormHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    RestTemplate restTemplate=new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(requestFactory);
    return restTemplate;
}
 
Example 5
Source Project: Milkomeda   File: EchoCloudConfig.java    License: MIT License 5 votes vote down vote up
@LoadBalanced
@Bean("echoCloudRestTemplate")
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public RestTemplate simpleRestTemplate(RestTemplateBuilder builder, ClientHttpRequestFactory factory) {
    RestTemplate restTemplate = builder.build();
    restTemplate.setRequestFactory(factory);
    restTemplate.setErrorHandler(new EchoResponseErrorHandler());
    return restTemplate;
}
 
Example 6
@Bean
@ConditionalOnMissingBean(DataFlowOperations.class)
public DataFlowOperations dataFlowOperations() throws Exception{
	RestTemplate template = DataFlowTemplate.prepareRestTemplate(restTemplate);
	final HttpClientConfigurer httpClientConfigurer = HttpClientConfigurer.create(new URI(properties.getServerUri()))
			.skipTlsCertificateVerification(properties.isSkipSslValidation());

	if (StringUtils.hasText(this.properties.getAuthentication().getAccessToken())) {
		template.getInterceptors().add(new OAuth2AccessTokenProvidingClientHttpRequestInterceptor(this.properties.getAuthentication().getAccessToken()));
		logger.debug("Configured OAuth2 Access Token for accessing the Data Flow Server");
	}
	else if (StringUtils.hasText(this.properties.getAuthentication().getClientId())) {
		ClientRegistration clientRegistration = clientRegistrations.findByRegistrationId(DEFAULT_REGISTRATION_ID);
		template.getInterceptors().add(clientCredentialsTokenResolvingInterceptor(clientRegistration,
				clientRegistrations, this.properties.getAuthentication().getClientId()));
		logger.debug("Configured OAuth2 Client Credentials for accessing the Data Flow Server");
	}
	else if(!StringUtils.isEmpty(properties.getAuthentication().getBasic().getUsername()) &&
			!StringUtils.isEmpty(properties.getAuthentication().getBasic().getPassword())){
		httpClientConfigurer.basicAuthCredentials(properties.getAuthentication().getBasic().getUsername(),
				properties.getAuthentication().getBasic().getPassword());
		template.setRequestFactory(httpClientConfigurer.buildClientHttpRequestFactory());
	}
	else if (oauth2ClientProperties != null && !oauth2ClientProperties.getRegistration().isEmpty()
			&& StringUtils.hasText(properties.getAuthentication().getOauth2().getUsername())
			&& StringUtils.hasText(properties.getAuthentication().getOauth2().getPassword())) {
		ClientHttpRequestInterceptor bearerTokenResolvingInterceptor = bearerTokenResolvingInterceptor(
				oauth2ClientProperties, properties.getAuthentication().getOauth2().getUsername(),
				properties.getAuthentication().getOauth2().getPassword(),
				properties.getAuthentication().getOauth2().getClientRegistrationId());
		template.getInterceptors().add(bearerTokenResolvingInterceptor);
		logger.debug("Configured OAuth2 Bearer Token resolving for accessing the Data Flow Server");
	}
	else {
		logger.debug("Not configuring security for accessing the Data Flow Server");
	}

	return new DataFlowTemplate(new URI(properties.getServerUri()), template);
}
 
Example 7
Source Project: lite-tracer   File: RestTemplateWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取包装trace信息之后的RestTemplate
 * @return
 */
public RestTemplate getRestTemlate() {
    // 使用拦截器包装http header
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(new ArrayList<ClientHttpRequestInterceptor>() {
        {
            add((request, body, execution) -> {
                String traceId = RequestContext.getTraceId();
                String spanId = RequestContext.getSpanId();
                String parentSpanId = RequestContext.getParentSpanId();

                if (StringUtils.isNotEmpty(traceId)) {
                    request.getHeaders().add(Constants.HTTP_HEADER_TRACE_ID, traceId);
                }
                if (StringUtils.isNotEmpty(spanId)) {
                    request.getHeaders().add(Constants.HTTP_HEADER_SPAN_ID, spanId);
                }
                if (StringUtils.isNotEmpty(parentSpanId)) {
                    request.getHeaders().add(Constants.HTTP_HEADER_PARENT_SPAN_ID, parentSpanId);
                }
                return execution.execute(request, body);
            });
        }
    });

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    // 注意此处需开启缓存,否则会报getBodyInternal方法“getBody not supported”错误
    factory.setBufferRequestBody(true);
    restTemplate.setRequestFactory(factory);
    return restTemplate;
}
 
Example 8
Source Project: cf-java-client-sap   File: RestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public RestTemplate createRestTemplate(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
    RestTemplate restTemplate = new LoggingRestTemplate();
    restTemplate.setRequestFactory(createRequestFactory(httpProxyConfiguration, trustSelfSignedCerts));
    restTemplate.setErrorHandler(new CloudControllerResponseErrorHandler());
    restTemplate.setMessageConverters(getHttpMessageConverters());

    return restTemplate;
}
 
Example 9
private static RestTemplate createNotifierRestTemplate(NotifierProxyProperties proxyProperties) {
	RestTemplate restTemplate = new RestTemplate();
	if (proxyProperties.getHost() != null) {
		SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
		Proxy proxy = new Proxy(Proxy.Type.HTTP,
				new InetSocketAddress(proxyProperties.getHost(), proxyProperties.getPort()));
		requestFactory.setProxy(proxy);
		restTemplate.setRequestFactory(requestFactory);
	}
	return restTemplate;
}
 
Example 10
private void setTimeout(RestTemplate restTemplate, int connectTimeout, int readTimeout) {
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(readTimeout);
    rf.setConnectTimeout(connectTimeout);
}
 
Example 11
private void setTimeout(RestTemplate restTemplate, int connectTimeout, int readTimeout) {
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(readTimeout);
    rf.setConnectTimeout(connectTimeout);
}
 
Example 12
private static void setTimeout(RestTemplate restTemplate, int connectTimeout, int readTimeout) {
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(readTimeout);
    rf.setConnectTimeout(connectTimeout);
}
 
Example 13
@Override
public void customize(RestTemplate restTemplate) {
    HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
    HttpClient httpClient = HttpClientBuilder.create()
        .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
                return super.determineProxy(target, request, context);
            }
        })
        .build();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
 
Example 14
/**
 * Configure a {@link RestTemplate} for communication with a CredHub server.
 * @param restTemplate an existing {@link RestTemplate} to configure
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 */
private static void configureRestTemplate(RestTemplate restTemplate, String baseUri,
		ClientHttpRequestFactory clientHttpRequestFactory) {
	restTemplate.setRequestFactory(clientHttpRequestFactory);
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(baseUri));
	restTemplate.getInterceptors().add(new CredHubRequestInterceptor());
	restTemplate.setMessageConverters(
			Arrays.asList(new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
					new MappingJackson2HttpMessageConverter(JsonUtils.buildObjectMapper())));
}
 
Example 15
private static RestTemplate createTokenServerRestTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
	RestTemplate restOperations = new RestTemplate(
			Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
	restOperations.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
	restOperations.setRequestFactory(clientHttpRequestFactory);
	return restOperations;
}
 
Example 16
RestTemplate configure(RequestMappingConfiguration configuration) {
    ClientHttpRequestFactory requestFactory = clientHttpRequestFactoryCreator.createRequestFactory(timeoutConfiguration);
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(createHttpRequestInterceptors(configuration));
    interceptors.addAll(clientHttpRequestInterceptors);
    RestTemplate restTemplate = new RetryAwareRestTemplate();
    restTemplate.setRequestFactory(requestFactory);
    restTemplate.setErrorHandler(new NoExceptionErrorHandler());
    restTemplate.setInterceptors(interceptors);
    return restTemplate;
}
 
Example 17
Source Project: tutorials   File: RestTemplateLoggingLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenHttpClientConfiguration_whenSendGetForRequestEntity_thenRequestResponseFullLog() {

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

    final ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/persons", "my request body", String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
 
Example 18
@org.springframework.context.annotation.Bean("compensableRestTemplate")
@org.springframework.cloud.client.loadbalancer.LoadBalanced
public RestTemplate transactionTemplate(@Autowired ClientHttpRequestFactory requestFactory) {
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setRequestFactory(requestFactory);

	SpringCloudBeanRegistry registry = SpringCloudBeanRegistry.getInstance();
	registry.setRestTemplate(restTemplate);

	return restTemplate;
}
 
Example 19
/**
 * @param clientRegistrations Can be null. Only required for Client Credentials Grant authentication
 * @param clientCredentialsTokenResponseClient Can be null. Only required for Client Credentials Grant authentication
 * @return DataFlowOperations
 */
@Bean
public DataFlowOperations dataFlowOperations(
	@Autowired(required = false) ClientRegistrationRepository  clientRegistrations,
	@Autowired(required = false) OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient) {

	final RestTemplate restTemplate = DataFlowTemplate.getDefaultDataflowRestTemplate();
	validateUsernamePassword(this.properties.getDataflowServerUsername(), this.properties.getDataflowServerPassword());

	HttpClientConfigurer clientHttpRequestFactoryBuilder = null;

	if (this.properties.getOauth2ClientCredentialsClientId() != null
			|| StringUtils.hasText(this.properties.getDataflowServerAccessToken())
			|| (StringUtils.hasText(this.properties.getDataflowServerUsername())
					&& StringUtils.hasText(this.properties.getDataflowServerPassword()))) {
		clientHttpRequestFactoryBuilder = HttpClientConfigurer.create(this.properties.getDataflowServerUri());
	}

	String accessTokenValue = null;

	if (this.properties.getOauth2ClientCredentialsClientId() != null) {
		final ClientRegistration clientRegistration = clientRegistrations.findByRegistrationId("default");
		final OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
		final OAuth2AccessTokenResponse res = clientCredentialsTokenResponseClient.getTokenResponse(grantRequest);
		accessTokenValue = res.getAccessToken().getTokenValue();
		logger.debug("Configured OAuth2 Client Credentials for accessing the Data Flow Server");
	}
	else if (StringUtils.hasText(this.properties.getDataflowServerAccessToken())) {
		accessTokenValue = this.properties.getDataflowServerAccessToken();
		logger.debug("Configured OAuth2 Access Token for accessing the Data Flow Server");
	}
	else if (StringUtils.hasText(this.properties.getDataflowServerUsername())
			&& StringUtils.hasText(this.properties.getDataflowServerPassword())) {
		accessTokenValue = null;
		clientHttpRequestFactoryBuilder.basicAuthCredentials(properties.getDataflowServerUsername(), properties.getDataflowServerPassword());
		logger.debug("Configured basic security for accessing the Data Flow Server");
	}
	else {
		logger.debug("Not configuring basic security for accessing the Data Flow Server");
	}

	if (accessTokenValue != null) {
		restTemplate.getInterceptors().add(new OAuth2AccessTokenProvidingClientHttpRequestInterceptor(accessTokenValue));
	}

	if (clientHttpRequestFactoryBuilder != null) {
		restTemplate.setRequestFactory(clientHttpRequestFactoryBuilder.buildClientHttpRequestFactory());
	}

	return new DataFlowTemplate(this.properties.getDataflowServerUri(), restTemplate);
}
 
Example 20
/**
 * @param clientRegistrations Can be null. Only required for Client Credentials Grant authentication
 * @param clientCredentialsTokenResponseClient Can be null. Only required for Client Credentials Grant authentication
 * @return DataFlowOperations
 */
@Bean
public DataFlowOperations dataFlowOperations(
	@Autowired(required = false) ClientRegistrationRepository clientRegistrations,
	@Autowired(required = false) OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient) {

	final RestTemplate restTemplate = DataFlowTemplate.getDefaultDataflowRestTemplate();
	validateUsernamePassword(this.properties.getDataflowServerUsername(), this.properties.getDataflowServerPassword());

	HttpClientConfigurer clientHttpRequestFactoryBuilder = null;

	if (this.properties.getOauth2ClientCredentialsClientId() != null
			|| StringUtils.hasText(this.properties.getDataflowServerAccessToken())
			|| (StringUtils.hasText(this.properties.getDataflowServerUsername())
					&& StringUtils.hasText(this.properties.getDataflowServerPassword()))) {
		clientHttpRequestFactoryBuilder = HttpClientConfigurer.create(this.properties.getDataflowServerUri());
	}

	String accessTokenValue = null;

	if (this.properties.getOauth2ClientCredentialsClientId() != null) {
		final ClientRegistration clientRegistration = clientRegistrations.findByRegistrationId("default");
		final OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
		final OAuth2AccessTokenResponse res = clientCredentialsTokenResponseClient.getTokenResponse(grantRequest);
		accessTokenValue = res.getAccessToken().getTokenValue();
		logger.debug("Configured OAuth2 Client Credentials for accessing the Data Flow Server");
	}
	else if (StringUtils.hasText(this.properties.getDataflowServerAccessToken())) {
		accessTokenValue = this.properties.getDataflowServerAccessToken();
		logger.debug("Configured OAuth2 Access Token for accessing the Data Flow Server");
	}
	else if (StringUtils.hasText(this.properties.getDataflowServerUsername())
			&& StringUtils.hasText(this.properties.getDataflowServerPassword())) {
		accessTokenValue = null;
		clientHttpRequestFactoryBuilder.basicAuthCredentials(properties.getDataflowServerUsername(), properties.getDataflowServerPassword());
		logger.debug("Configured basic security for accessing the Data Flow Server");
	}
	else {
		logger.debug("Not configuring basic security for accessing the Data Flow Server");
	}

	if (accessTokenValue != null) {
		restTemplate.getInterceptors().add(new OAuth2AccessTokenProvidingClientHttpRequestInterceptor(accessTokenValue));
	}

	if (clientHttpRequestFactoryBuilder != null) {
		restTemplate.setRequestFactory(clientHttpRequestFactoryBuilder.buildClientHttpRequestFactory());
	}

	return new DataFlowTemplate(this.properties.getDataflowServerUri(), restTemplate);
}