Java Code Examples for org.springframework.web.client.RestTemplate#setRequestFactory()
The following examples show how to use
org.springframework.web.client.RestTemplate#setRequestFactory() .
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: ApiClient.java From tutorials with MIT License | 6 votes |
/** * 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 File: ApiClient.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * 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 |
/** * 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: AdminServerNotifierAutoConfiguration.java From spring-boot-admin with Apache License 2.0 | 5 votes |
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 5
Source File: SpringCloudConfiguration.java From ByteTCC with GNU Lesser General Public License v3.0 | 5 votes |
@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 6
Source File: RestTemplateLoggingLiveTest.java From tutorials with MIT License | 5 votes |
@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 7
Source File: RestTemplateConfiguration.java From charon-spring-boot-starter with Apache License 2.0 | 5 votes |
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 8
Source File: CredHubRestTemplateFactory.java From spring-credhub with Apache License 2.0 | 5 votes |
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 9
Source File: CredHubRestTemplateFactory.java From spring-credhub with Apache License 2.0 | 5 votes |
/** * 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 10
Source File: RestTemplateCustomizerLiveTest.java From tutorials with MIT License | 5 votes |
@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 11
Source File: GradleUpdateHandler.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
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 12
Source File: GoogleSearchProviderImpl.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
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 13
Source File: BintraySearchProviderImpl.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
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 14
Source File: DefaultAuthServiceImpl.java From SENS with GNU General Public License v3.0 | 5 votes |
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 15
Source File: RestUtil.java From cf-java-client-sap with Apache License 2.0 | 5 votes |
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 16
Source File: RestTemplateWrapper.java From lite-tracer with Apache License 2.0 | 5 votes |
/** * 获取包装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 17
Source File: DataFlowClientAutoConfiguration.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@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 18
Source File: EchoCloudConfig.java From Milkomeda with MIT License | 5 votes |
@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 19
Source File: DataFlowConfiguration.java From spring-cloud-dataflow with Apache License 2.0 | 4 votes |
/** * @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
Source File: DataFlowConfiguration.java From composed-task-runner with Apache License 2.0 | 4 votes |
/** * @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); }