@Test public void testHome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue( "Result is not Matched with Server Response",entity.getBody().contains("welcome to the application")); }
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; }
@Bean public ClientHttpRequestFactory requestFactory() { // Disable auto redirect on 3xx HTTP responses CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build(); HttpComponentsClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient); // read timeout if(!StringUtils.isEmpty(readTimeout)) { rf.setReadTimeout(Integer.valueOf(readTimeout) * 1000); } // connect timeout if(!StringUtils.isEmpty(connectTimeout)) { rf.setConnectTimeout(Integer.valueOf(connectTimeout) * 1000); } return rf; }
public void afterPropertiesSet() throws UnsupportedEncodingException { Collection<Header> defaultHeaders = new ArrayList<Header>(); Header header = new BasicHeader("Authorization", "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8"))); defaultHeaders.add(header); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("apollo", "")); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(defaultHeaders).build(); restTemplate = new RestTemplate(httpMessageConverters.getConverters()); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); requestFactory.setConnectTimeout(portalConfig.connectTimeout()); requestFactory.setReadTimeout(portalConfig.readTimeout()); restTemplate.setRequestFactory(requestFactory); }
@Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); }
public RestTemplate createTemplate(final String host, final Integer port, final String username, final String password) { Preconditions.checkArgument(StringUtils.isNotBlank(host)); Preconditions.checkArgument(port != null); Preconditions.checkArgument(StringUtils.isNotBlank(username)); Preconditions.checkArgument(StringUtils.isNotBlank(password)); final AuthScope authscope = new AuthScope(host, port.intValue()); final Credentials credentials = new UsernamePasswordCredentials(username, password); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authscope, credentials); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); final CloseableHttpClient httpClient = clientBuilder.build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); }
/** * Construct rest template with data app uri. * * @param builder rest template builder * @param dataAppUri data app uri from application.properties */ public MovieRepository(RestTemplateBuilder builder, @Value("${moviedb.webapp.dataAppUri}") String dataAppUri) { logger.debug("data app:" + dataAppUri); String trimmedURL = dataAppUri.trim().toLowerCase(); String dataAppApiUrl; if (trimmedURL.startsWith("http://") || trimmedURL.startsWith("https://")) { dataAppApiUrl = trimmedURL + "/api/v1"; } else { dataAppApiUrl = "http://" + trimmedURL + "/api/v1"; } logger.debug("data app api root url: " + dataAppApiUrl); restTemplate = builder.rootUri(dataAppApiUrl).build(); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); }
@Test public void testLogin() { try { String authUrl = String.format(AUTH_URL_BASE, port); JsonObject request = Json.createObjectBuilder() .add("id", DEFAULT_ID) .add("key", DEFAULT_KEY) .build(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers); RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); ResponseEntity<String> response = rest.exchange(authUrl, HttpMethod.POST, entity, String.class); assertEquals(200, response.getStatusCodeValue()); JsonReader reader = Json.createReader(new StringReader(response.getBody())); JsonObject o = reader.readObject(); String token = o.getString("token"); assertTrue(!StringUtils.isEmpty(token)); logger.info(token); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }
@Test public void testLoginUpperCaseUUIDs() { try { String authUrl = String.format(AUTH_URL_BASE, port); JsonObject request = Json.createObjectBuilder() .add("id", DEFAULT_ID_UPPER) .add("key", DEFAULT_KEY_UPPER) .build(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(request.toString(), headers); RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); ResponseEntity<String> response = rest.exchange(authUrl, HttpMethod.POST, entity, String.class); assertEquals(200, response.getStatusCodeValue()); JsonReader reader = Json.createReader(new StringReader(response.getBody())); JsonObject o = reader.readObject(); String token = o.getString("token"); assertTrue(!StringUtils.isEmpty(token)); logger.info(token); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }
/** * Creates the security rest template. * * @throws KeyManagementException the key management exception * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception */ private void createSecurityRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException{ TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); HttpClient httpClient = HttpClientBuilder.create() .disableCookieManagement() .useSystemProperties() .setSSLSocketFactory(csf) .build(); requestFactory.setHttpClient(httpClient); this.restTemplate = new RestTemplate(requestFactory); }
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options) throws GeneralSecurityException, IOException { HttpClientBuilder httpClientBuilder = HttpClients.custom() .setSSLContext(SSLContext.getDefault()) .useSystemProperties(); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setAuthenticationEnabled(true); if (options.getConnectionTimeout() != null) { requestConfigBuilder.setConnectTimeout(options.getConnectionTimeout()); } if (options.getReadTimeout() != null) { requestConfigBuilder.setSocketTimeout(options.getReadTimeout()); } httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
@Test public void contextLoads() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute?env=stage&key=PING", HttpMethod.GET, entity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals(new Integer(0), response.getBody().getCode()); Assert.assertNotNull(response.getBody().getOutput()); httpClient.close(); }
@Test public void hello() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute/hello", HttpMethod.GET, entity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
@Test public void executeCommands() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=DEPLOY&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Bounce() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=BOUNCE&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebmobile&env=dev", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Status() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=STATUS&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_NoKey() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<Object> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute", HttpMethod.POST, requestEntity, Object.class); Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
@Override public ResponseEntity<String> submit(JCurlRequestOptions requestOptions) throws Exception { ResponseEntity<String> stringResponseEntity = null; try (CloseableHttpClient hc = createCloseableHttpClient()) { for (int i = 0; i < requestOptions.getCount(); i++) { final HttpHeaders headers = new HttpHeaders(); for(Map.Entry<String,String> e : requestOptions.getHeaderMap().entrySet()) { headers.put(e.getKey(), Collections.singletonList(e.getValue())); } final HttpEntity<Void> requestEntity = new HttpEntity<>(headers); RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory(hc)); stringResponseEntity = template.exchange(requestOptions.getUrl(), HttpMethod.GET, requestEntity, String.class); System.out.println(stringResponseEntity.getBody()); } return stringResponseEntity; } }
public HttpStatus isUpToDate(ServerFile serverFile) { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(requestFactory); restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter()); HttpHeaders requestHeaders = new HttpHeaders(); //requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM)); requestHeaders.setAccept(Collections.singletonList(MediaType.ALL)); if (serverFile.geteTag() != null) { requestHeaders.setIfNoneMatch(serverFile.geteTag()); } if (serverFile.getLastModified() != null) { requestHeaders.setLastModified(serverFile.getLastModified()); } HttpEntity<String> entity = new HttpEntity<String>(requestHeaders); ResponseEntity<byte[]> response = restTemplate.exchange(serverFile.getRemoteUrl(), HttpMethod.GET, entity, byte[].class); return response.getStatusCode(); }
private ResponseEntity<byte[]> exchange(ServerFile serverFile) { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(requestFactory); restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter()); HttpHeaders requestHeaders = new HttpHeaders(); //requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM)); requestHeaders.setAccept(Collections.singletonList(MediaType.ALL)); if (serverFile.geteTag() != null) { requestHeaders.setIfNoneMatch(serverFile.geteTag()); } if (serverFile.getLastModified() != null) { requestHeaders.setLastModified(serverFile.getLastModified()); } HttpEntity<String> entity = new HttpEntity<String>(requestHeaders); return restTemplate.exchange(serverFile.getRemoteUrl(), HttpMethod.GET, entity, byte[].class); }
public String bodyWithDeleteRequest(String url, String deleteBody) throws Exception { restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() { @Override protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { if (HttpMethod.DELETE == httpMethod) { return new HttpEntityEnclosingDeleteRequest(uri); } return super.createHttpUriRequest(httpMethod, uri); } }); ResponseEntity<String> exchange = restTemplate.exchange( url, HttpMethod.DELETE, new HttpEntity<String>(deleteBody), String.class); return exchange.toString(); }
@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)); }
@Test public void testWelcome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("welcome to the application "+System.getProperty("user.name"), entity.getBody()); }
@Test public void test1() { 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("add cart"); Map<String, Object> cartItem = new HashMap<>(); cartItem.put("itemId", 1); cartItem.put("quantity", 3); System.out.println(restTemplate.postForObject("http://localhost:8080/cart/items", cartItem, Object.class)); System.out.println("show cart"); System.out.println(restTemplate.getForObject("http://localhost:8080/cart", Object.class)); System.out.println("checkout"); Map<String, Object> map = new HashMap<>(); map.put("name", "Shin Tanimoto"); map.put("address", "Yokohama Japan"); map.put("telephone", "+81 123 456 7890"); map.put("cardNumber", "1234 5678 8765 4321"); map.put("cardExpire", "12/20"); map.put("cardName", "Shin Tanimoto"); System.out.println(restTemplate.postForObject("http://localhost:8080/order", map, Object.class)); }
@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)); }
@Test public void sslDisabled() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); factory.setSsl(ssl); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); }
@Test public void sslGetScheme() throws Exception { // gh-2232 AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
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; }
@Test public void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test(expected = IOException.class) public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); getResponse(getLocalUrl("https", "/test.txt"), requestFactory); }
@Test public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers)); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
@Test public void compressionWithoutContentSizeHeader() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); Compression compression = new Compression(); compression.setEnabled(true); factory.setCompression(compression); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(false, true), "/hello")); this.container.start(); TestGzipInputStreamFactory inputStreamFactory = new TestGzipInputStreamFactory(); Map<String, InputStreamFactory> contentDecoderMap = Collections .singletonMap("gzip", (InputStreamFactory) inputStreamFactory); getResponse(getLocalUrl("/hello"), new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() .setContentDecoderRegistry(contentDecoderMap).build())); assertThat(inputStreamFactory.wasCompressionUsed()).isTrue(); }
@Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { @Override public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (target.getHostName().equals("192.168.0.5")) { return null; } return super.determineProxy(target, request, context); } }).build(); restTemplate.setRequestFactory( new HttpComponentsClientHttpRequestFactory(httpClient)); }
public SmallTimeoutRestTemplateWorker(final String url, final MetricRegistry registry, final String name, final int timeout) { final HttpClient httpClient = HttpClientBuilder.create() .setMaxConnTotal(MAX_CONN_TOTAL) // .setMaxConnPerRoute(MAX_CONN_PER_ROUTE) .build(); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); factory.setReadTimeout(timeout); factory.setConnectionRequestTimeout(timeout); factory.setConnectTimeout(timeout); this.restTemplate = new RestTemplate(factory); this.url = url; this.registry = registry; this.name = name; this.timeout = timeout; }
public BigPoolRestTemplateWorker(final String url, final MetricRegistry registry, final String name, final int connectTimeout, final int readTimeout) { final HttpClient httpClient = HttpClientBuilder.create() .setMaxConnTotal(MAX_CONN_TOTAL) // .setMaxConnPerRoute(MAX_CONN_PER_ROUTE) .build(); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); factory.setConnectionRequestTimeout(connectTimeout); // Get from manager. factory.setConnectTimeout(connectTimeout); // Create connection. factory.setReadTimeout(readTimeout); // Socket. this.restTemplate = new RestTemplate(factory); this.url = url; this.registry = registry; this.name = name; this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; }