List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:com.muk.services.configuration.ServiceConfig.java
@Bean public CloseableHttpClient nonPerfomantHttpClient() { final HttpClientConnectionManager manager = poolingConnectionManager(); final Builder reqConfig = RequestConfig.custom(); reqConfig.setConnectionRequestTimeout(20000); reqConfig.setSocketTimeout(10000);//from w w w. j a v a 2s. co m reqConfig.setCircularRedirectsAllowed(false); final HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(manager) .setDefaultRequestConfig(reqConfig.build()).setKeepAliveStrategy(nonPerformantKeepAliveStrategy()) .disableConnectionState().disableCookieManagement().addInterceptorLast(mukRequestInterceptor()); staleConnectionExecutor().execute(new IdleConnectionMonitor(manager)); return builder.build(); }
From source file:com.xebialabs.overthere.winrm.WinRmClient.java
/** * Internal sendRequest, performs the HTTP request and returns the result document. *///w w w . ja v a 2s . co m private Document doSendRequest(final Document requestDocument, final SoapAction soapAction) { final HttpClientBuilder client = HttpClientBuilder.create(); HttpClientConnectionManager connectionManager = getHttpClientConnectionManager(); try { configureHttpClient(client); try (CloseableHttpClient httpClient = client.build()) { final HttpContext context = new BasicHttpContext(); final HttpPost request = new HttpPost(targetURL.toURI()); if (soapAction != null) { request.setHeader("SOAPAction", soapAction.getValue()); } final String requestBody = toString(requestDocument); logger.trace("Request:\nPOST {}\n{}", targetURL, requestBody); final HttpEntity entity = createEntity(requestBody); request.setEntity(entity); final HttpResponse response = httpClient.execute(request, context); logResponseHeaders(response); Document responseDocument = null; try { final String responseBody = handleResponse(response, context); responseDocument = DocumentHelper.parseText(responseBody); logDocument("Response body:", responseDocument); } catch (WinRmRuntimeIOException e) { if (response.getStatusLine().getStatusCode() == 200) { throw e; } } if (response.getStatusLine().getStatusCode() != 200) { throw new WinRmRuntimeIOException(String.format("Unexpected HTTP response on %s: %s (%s)", targetURL, response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode())); } return responseDocument; } finally { connectionManager.shutdown(); } } catch (WinRmRuntimeIOException exc) { throw exc; } catch (Exception exc) { throw new WinRmRuntimeIOException("Error when sending request to " + targetURL, requestDocument, null, exc); } }
From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java
/** * Create http client//from ww w. j av a 2 s.c o m */ private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (props.getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"), Integer.parseInt(props.getProperty("http.proxyPort")))); } if (props.getProperty("http.proxyUser") != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials( props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd"))); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } httpClient = httpClientBuilder.build(); } return httpClient; }
From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java
/** * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds * * @param keyPair the keypair to generate the csr for * @throws IOException if there is a problem during the process * @return the resulting certificate chain *//*from www . ja v a 2s . c o m*/ public X509Certificate[] perform(KeyPair keyPair) throws IOException { try { List<X509Certificate> certificates = new ArrayList<>(); HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.useProtocol("TLSv1.2"); // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory( sslContextBuilder.build(), caHostname, certificates)); String jsonResponseString; int responseCode; try (CloseableHttpClient client = httpClientBuilder.build()) { JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm); TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest( TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request)); HttpPost httpPost = new HttpPost(); httpPost.setEntity( new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest))); if (logger.isInfoEnabled()) { logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port); } try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) { jsonResponseString = IOUtils.toString( new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8); responseCode = response.getStatusLine().getStatusCode(); } } if (responseCode != Response.SC_OK) { throw new IOException( RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString); } if (certificates.size() != 1) { throw new IOException(EXPECTED_ONE_CERTIFICATE); } TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class); if (!tlsCertificateAuthorityResponse.hasHmac()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC); } X509Certificate caCertificate = certificates.get(0); byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey()); if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) { throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE); } if (!tlsCertificateAuthorityResponse.hasCertificate()) { throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE); } X509Certificate x509Certificate = TlsHelper .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate())); x509Certificate.verify(caCertificate.getPublicKey()); if (logger.isInfoEnabled()) { logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal()); } return new X509Certificate[] { x509Certificate, caCertificate }; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } }
From source file:com.github.tmyroadctfig.icloud4j.ICloudService.java
/** * Creates a new iCloud service instance * * @param clientId the client ID.// w w w .j ava 2s. c o m */ @SuppressWarnings("deprecation") public ICloudService(ICloudSession session) { this.session = session; try { HttpClientBuilder clientBuilder = HttpClientBuilder.create().setDefaultCookieStore(getCookieStore()); if (!Strings.isNullOrEmpty(PROXY_HOST)) { clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT)); } if (DISABLE_SSL_CHECKS) { clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext( new SSLContextBuilder().loadTrustMaterial(null, (x509CertChain, authType) -> true).build()); } httpClient = clientBuilder.build(); } catch (Exception e) { throw Throwables.propagate(e); } idmsaService = new IdmsaService(this); }
From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java
public synchronized HttpClient getNativeHttpClient() { if (myHttpClient == null) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); connectionManager.setMaxTotal(getPoolMaxTotal()); connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute()); // @formatter:off RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout()) .setConnectTimeout(getConnectTimeout()) .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true) .setProxy(myProxy).build(); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement(); if (myProxy != null && StringUtils.isNotBlank(getProxyUsername()) && StringUtils.isNotBlank(getProxyPassword())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()), new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword())); builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); builder.setDefaultCredentialsProvider(credsProvider); }//from w w w . j a v a 2 s . c om myHttpClient = builder.build(); // @formatter:on } return myHttpClient; }
From source file:com.conwet.wirecloud.ide.WirecloudAPI.java
protected CloseableHttpClient createHttpClient(URL url) { HttpClientBuilder hcBuilder = HttpClients.custom(); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost;//from w w w. j a va 2 s.c o m try { proxyDataForHost = proxyService.select(url.toURI()); } catch (URISyntaxException e) { throw new AssertionError(e); } for (IProxyData iProxyData : proxyDataForHost) { HttpHost proxy = new HttpHost(iProxyData.getHost(), iProxyData.getPort(), iProxyData.getType()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); hcBuilder.setRoutePlanner(routePlanner); } return hcBuilder.build(); }
From source file:com.delphix.delphix.DelphixEngine.java
public DelphixEngine(DelphixEngine engine) { this.engineAddress = engine.engineAddress; this.engineUsername = engine.engineUsername; this.enginePassword = engine.enginePassword; RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(60 * 1000); requestBuilder = requestBuilder.setConnectionRequestTimeout(60 * 1000); requestBuilder = requestBuilder.setSocketTimeout(60 * 1000); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); client = builder.build(); }
From source file:com.delphix.delphix.DelphixEngine.java
@DataBoundConstructor public DelphixEngine(String engineAddress, String engineUsername, String enginePassword) { this.engineAddress = engineAddress; this.engineUsername = engineUsername; this.enginePassword = enginePassword; RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(60 * 1000); requestBuilder = requestBuilder.setConnectionRequestTimeout(60 * 1000); requestBuilder = requestBuilder.setSocketTimeout(60 * 1000); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); client = builder.build(); }