org.springframework.http.client.HttpComponentsClientHttpRequestFactory Java Examples

The following examples show how to use org.springframework.http.client.HttpComponentsClientHttpRequestFactory. 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: RestClientCertTestConfiguration.java    From spring-boot-rest-clientcertificate with MIT License 8 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {

    SSLContext sslContext = SSLContextBuilder
            .create()
            .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"), allPassword, allPassword)
            .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword)
            .build();

    HttpClient client = HttpClients.custom()
            .setSSLContext(sslContext)
            .build();

    return builder
            .requestFactory(new HttpComponentsClientHttpRequestFactory(client))
            .build();
}
 
Example #2
Source File: AbstractKeycloakIdentityProviderTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Rest template setup including a disabled SSL certificate validation.
 * @throws Exception in case of errors
 */
private static void setupRestTemplate() throws Exception {
	final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
               .loadTrustMaterial(null, acceptingTrustStrategy)
               .build();
	final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
	final HttpClient httpClient = HttpClientBuilder.create()
    		.setRedirectStrategy(new LaxRedirectStrategy())
    		.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
    		.build();
	factory.setHttpClient(httpClient);
	restTemplate.setRequestFactory(factory);		

	for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
		if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
			restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
			break;
		}
	}
}
 
Example #3
Source File: RequestPartIntegrationTests.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@Before
public void setup() {
	ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
	emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

	List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
	converters.add(emptyBodyConverter);
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new ResourceHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
	converter.setPartConverters(converters);

	restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
	restTemplate.setMessageConverters(Collections.singletonList(converter));
}
 
Example #4
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #5
Source File: RestClientLiveManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {

    final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("https", sslsf)
            .register("http", new PlainConnectionSocketFactory())
            .build();

    final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    final CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setConnectionManager(connectionManager)
            .build();

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example #6
Source File: RequestPartIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
	emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

	List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
	converters.add(emptyBodyConverter);
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new ResourceHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
	converter.setPartConverters(converters);

	restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
	restTemplate.setMessageConverters(Collections.singletonList(converter));
}
 
Example #7
Source File: WxApiHttpRequestFactory.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 获取连接工厂
 *
 * @return the result
 */
private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpClient httpClient = getHttpClient();
    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(wxProperties.getInvoker().getConnectTimeout());
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(wxProperties.getInvoker().getReadTimeout());
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(wxProperties.getInvoker().getConnectionRequestTimeout());
    return clientHttpRequestFactory;
}
 
Example #8
Source File: RestTemplateConfig.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * httpRequestFactory.
 * 
 * @return
 */
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(
            30, TimeUnit.SECONDS);
    // max connection
    pollingConnectionManager.setMaxTotal(constants.getRestTemplateMaxTotal());

    pollingConnectionManager.setDefaultMaxPerRoute(constants.getRestTemplateMaxPerRoute());
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // add Keep-Alive
    httpClientBuilder
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
            new HttpComponentsClientHttpRequestFactory(httpClient);
    clientHttpRequestFactory.setReadTimeout(constants.getHttp_read_timeOut());
    clientHttpRequestFactory.setConnectTimeout(constants.getHttp_connect_timeOut());
    return clientHttpRequestFactory;
}
 
Example #9
Source File: StoreApplicationTest.java    From e-commerce-example with Apache License 2.0 6 votes vote down vote up
@Test
	public void test3() {
		RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

		System.out.println("show catalog");
		System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));
		System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));
		System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));
		System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));

		System.out.println("add cart");
		Map<String, Object> cartItem = new HashMap<>();
		cartItem.put("itemId", 2);
		cartItem.put("quantity", 1);
		System.out.println(restTemplate.postForObject("http://localhost:8080/cart/items", cartItem, Object.class));
}
 
Example #10
Source File: ClientHttpRequestFactoryFactoryIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void httpComponentsClientUsingPemShouldWork() throws Exception {

	File caCertificate = new File(Settings.findWorkDir(), "ca/certs/ca.cert.pem");
	SslConfiguration sslConfiguration = SslConfiguration.forTrustStore(SslConfiguration.KeyStoreConfiguration
			.of(new FileSystemResource(caCertificate)).withStoreType(SslConfiguration.PEM_KEYSTORE_TYPE));

	ClientHttpRequestFactory factory = HttpComponents.usingHttpComponents(new ClientOptions(), sslConfiguration);
	RestTemplate template = new RestTemplate(factory);

	String response = request(template);

	assertThat(factory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
	assertThat(response).isNotNull().contains("initialized");

	((DisposableBean) factory).destroy();
}
 
Example #11
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #12
Source File: AbstractIT.java    From bowman with Apache License 2.0 6 votes vote down vote up
protected AbstractIT() {
	baseUri = URI.create(System.getProperty("baseUrl", "http://localhost:8080"));
	
	clientFactory = Configuration.builder()
			.setBaseUri(baseUri)
			.setClientHttpRequestFactory(new BufferingClientHttpRequestFactory(
					new HttpComponentsClientHttpRequestFactory()))
			.setRestTemplateConfigurer(new RestTemplateConfigurer() {
				
				@Override
				public void configure(RestTemplate restTemplate) {
					restTemplate.getInterceptors().addAll(asList(
						new LoggingClientHttpRequestInterceptor(),
						createdEntityRecordingInterceptor
					));
				}
			})
			.build()
			.buildClientFactory();
}
 
Example #13
Source File: NexusArtifactClient.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public boolean deleteArtifact(String longUrl) {
    try {
        CloseableHttpClient httpClient;
        if (getUserName() != null && getPassword() != null) {
            URL url = new URL(getUrl());
            HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(getUserName(), getPassword()));
            httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClientBuilder.create().build();
        }
        RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        restTemplate.delete(new URI(longUrl));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example #14
Source File: AboutController.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private String getChecksum(String defaultValue, String url,
		String version) {
	String result = defaultValue;
	if (result == null && StringUtils.hasText(url)) {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		url = constructUrl(url, version);
		try {
			ResponseEntity<String> response
					= new RestTemplate(requestFactory).exchange(
					url, HttpMethod.GET, null, String.class);
			if (response.getStatusCode().equals(HttpStatus.OK)) {
				result = response.getBody();
			}
		}
		catch (HttpClientErrorException httpException) {
			// no action necessary set result to undefined
			logger.debug("Didn't retrieve checksum because", httpException);
		}
	}
	return result;
}
 
Example #15
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 #16
Source File: AbstractRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
public AbstractRestTemplateClient ignoreAuthenticateServer() {
    //backward compatible with android httpclient 4.3.x
    if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier();
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer");
    }
    return this;
}
 
Example #17
Source File: RestTemplateFactory.java    From spring-boot-chatbot with MIT License 6 votes vote down vote up
public static RestOperations getRestOperations(HttpComponentsClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate(factory);

    StringHttpMessageConverter stringMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
    ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(jackson2Converter);
    converters.add(stringMessageConverter);
    converters.add(byteArrayHttpMessageConverter);
    converters.add(formHttpMessageConverter);

    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
 
Example #18
Source File: WebServerStateSetterWorker.java    From jwala with Apache License 2.0 5 votes vote down vote up
public WebServerStateSetterWorker(@Qualifier("webServerInMemoryStateManagerService")
                                  final InMemoryStateManagerService<Identifier<WebServer>, WebServerReachableState> inMemoryStateManagerService,
                                  final WebServerService webServerService,
                                  final MessagingService messagingService,
                                  final GroupStateNotificationService groupStateNotificationService,
                                  @Qualifier("httpRequestFactory")
                                  final HttpComponentsClientHttpRequestFactory httpRequestFactory) {
    this.inMemoryStateManagerService = inMemoryStateManagerService;
    this.webServerService = webServerService;
    this.messagingService = messagingService;
    this.groupStateNotificationService = groupStateNotificationService;
    this.httpRequestFactory = httpRequestFactory;
}
 
Example #19
Source File: DockerRegistryValidator.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private RestTemplate configureRestTemplate() {
	CloseableHttpClient httpClient
			= HttpClients.custom()
			.setSSLHostnameVerifier(new NoopHostnameVerifier())
			.build();
	HttpComponentsClientHttpRequestFactory requestFactory
			= new HttpComponentsClientHttpRequestFactory();
	requestFactory.setHttpClient(httpClient);
	requestFactory.setConnectTimeout(dockerValidatiorProperties.getConnectTimeoutInMillis());
	requestFactory.setReadTimeout(dockerValidatiorProperties.getReadTimeoutInMillis());

	RestTemplate restTemplate = new RestTemplate(requestFactory);
	return restTemplate;
}
 
Example #20
Source File: AemServiceConfiguration.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Bean(name = "httpRequestFactory")
public HttpComponentsClientHttpRequestFactory getHttpComponentsClientHttpRequestFactory(
        @Value("${ping.http.connectionRequestTimeout:60000}") final int connectionRequestTimeout,
        @Value("${ping.http.readTimeout:600000}") final int readTimeout) {
    final HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    httpRequestFactory.setConnectionRequestTimeout(connectionRequestTimeout);
    httpRequestFactory.setReadTimeout(readTimeout);
    return httpRequestFactory;
}
 
Example #21
Source File: RestTemplateFakeReactiveFeign.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <T> ReactiveFeign.Builder<T> builder(ReactiveOptions options) {
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(
          HttpClientBuilder.create().build());
  if (options.getConnectTimeoutMillis() != null) {
    requestFactory.setConnectTimeout(options.getConnectTimeoutMillis());
  }
  if (options.getReadTimeoutMillis() != null) {
    requestFactory.setReadTimeout(options.getReadTimeoutMillis());
  }
  return builder(new RestTemplate(requestFactory),
      options.isTryUseCompression() != null && options.isTryUseCompression());
}
 
Example #22
Source File: StoreApplicationTest.java    From e-commerce-example with Apache License 2.0 5 votes vote down vote up
@Test
public void test4() {
	RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

	System.out.println("show catalog");
	System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));
	System.out.println(restTemplate.getForObject("http://localhost:8080/catalog", Object.class));
}
 
Example #23
Source File: MDSUrlService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public MDSUrlService(String url, String token, ObjectMapper objectMapper, Storage storage) {
    super();

    this.url = url;
    this.token = token;
    this.storage = storage;
    this.objectMapper = objectMapper;

    String unique = "";
    try {
        URI tempUrl = new URI(url);
        unique = tempUrl.getHost() + tempUrl.getPath();
    } catch (URISyntaxException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    namespace = Base64.getUrlEncoder().withoutPadding().encodeToString(unique.getBytes());

    HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);

    //TODO remove hardcoded solution to use right cert for production MDS
    if(token != null){
        jwtVerifier = new MDSJwtVerifier(retriveRootX509Certificate(PRODUCTION_FIDO_METADATA_SERVICE_ROOT_CERTIFICATE_CLASSPATH));
    }
    else{
        jwtVerifier = new MDSJwtVerifier(retriveRootX509Certificate(DEFAULT_FIDO_METADATA_SERVICE_ROOT_CERTIFICATE_CLASSPATH));
    }
}
 
Example #24
Source File: TeamUpAutoConfiguration.java    From spring-boot-chatbot with MIT License 5 votes vote down vote up
@Bean(name = FILE_REST_OPERATIONS)
public RestOperations fileRestOperations() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setConnectTimeout(20000);
    factory.setReadTimeout(20000);
    RestTemplate restTemplate = (RestTemplate) RestTemplateFactory.getRestOperations(factory);
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    return restTemplate;
}
 
Example #25
Source File: HelloController.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private ClientHttpRequestFactory getClientHttpRequestFactory() {
  int timeout = 5000;
  HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
      new HttpComponentsClientHttpRequestFactory();
  clientHttpRequestFactory.setConnectTimeout(timeout);
  return clientHttpRequestFactory;
}
 
Example #26
Source File: NavApiCient.java    From navigator-sdk with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
RestTemplate newRestTemplate() {
  if (isSSL) {
    CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLContext(sslContext)
        .setSSLHostnameVerifier(hostnameVerifier)
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory =
        new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
  } else {
    return new RestTemplate();
  }
}
 
Example #27
Source File: CookieStoreRestTemplate.java    From mojito with Apache License 2.0 5 votes vote down vote up
public void setCookieStoreAndUpdateRequestFactory(CookieStore cookieStore) {
    this.cookieStore = cookieStore;
    HttpClient hc = HttpClientBuilder
            .create()
            .setDefaultCookieStore(cookieStore)
            // we have to turn off auto redirect in the rest template because
            // when session expires, it will return a 302 and resttemplate
            // will automatically redirect to /login even before returning
            // the ClientHttpResponse in the interceptor
            .disableRedirectHandling()
            .build();

    setRequestFactory(new HttpComponentsClientHttpRequestFactory(hc));
}
 
Example #28
Source File: IdempotencyPluginTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void testHttpCreation() {
    try {
        Http.builder()
            .executor(Executors.newCachedThreadPool())
            .requestFactory(new HttpComponentsClientHttpRequestFactory())
            .build();
    } catch (ServiceConfigurationError e) {
        fail(e.getMessage());
    }
}
 
Example #29
Source File: HttpConfig.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns RestTemplate with keystore. This RestTemplate makes calls to other systems with a certificate to sign to
 * other systems by certificate. It is necessary to call systems like DiscoverySystem etc.
 *
 * @return RestTemplate, which uses certificate from keystore to authenticate
 */
@Bean
@Qualifier("restTemplateWithoutKeystore")
public RestTemplate restTemplateWithoutKeystore() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(secureHttpClientWithoutKeystore);
    return new RestTemplate(factory);
}
 
Example #30
Source File: RestClientLiveManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
    final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}