List of usage examples for org.apache.http.ssl SSLContextBuilder SSLContextBuilder
public SSLContextBuilder()
From source file:net.yacy.grid.http.ClientConnection.java
public static PoolingHttpClientConnectionManager getConnctionManager() { Registry<ConnectionSocketFactory> socketFactoryRegistry = null; try {/*from w w w .j a v a 2 s. c om*/ SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier()); socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", trustSelfSignedSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { Data.logger.warn("", e); } PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry) : new PoolingHttpClientConnectionManager(); // twitter specific options cm.setMaxTotal(2000); cm.setDefaultMaxPerRoute(200); return cm; }
From source file:ph.com.globe.connect.HttpRequest.java
/** * Send post request to the specified url. * //from ww w .j a va 2 s.com * @return CloseableHttpResponse * @throws HttpRequestException http request exception */ public CloseableHttpResponse sendPost() throws HttpRequestException { // try building up try { // initialize ssl context builder SSLContextBuilder builder = new SSLContextBuilder(); // set trust self signed strategy builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // initialize ssl socket connection factory SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build()); // default http client CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); // create request method HttpPost post = new HttpPost(this.url); // set default user agent post.setHeader("User-Agent", this.USER_AGENT); // set default content type post.setHeader("Content-Type", this.CONTENT_TYPE); // convert data to json string JSONObject data = new JSONObject(this.data); try { // set the string entity StringEntity entity = new StringEntity(data.toString()); // set post data post.setEntity(entity); } catch (UnsupportedEncodingException e) { // throw exception throw new HttpRequestException(e.getMessage()); } // try request try { // execute request and get the response CloseableHttpResponse response = client.execute(post); return response; } catch (IOException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } }
From source file:org.hawkular.client.core.jaxrs.RestFactory.java
private HttpClient getHttpClient() { CloseableHttpClient httpclient = null; try {/* w w w .j av a 2s . c o m*/ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { _logger.error("Failed to create HTTPClient: {}", e); } return httpclient; }
From source file:com.threatconnect.sdk.conn.ConnectionUtil.java
/** * Adds the ability to trust self signed certificates for this HttpClientBuilder * /*from ww w. j av a 2 s. c o m*/ * @param httpClientBuilder * the HttpClientBuilder to apply these settings to */ public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // allow all return true; } }); httpClientBuilder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex); } }
From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from www .j a v a2s . co m String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }
From source file:de.elomagic.maven.http.HTTPMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {//from w w w . j av a 2s. co m Executor executor; if (httpsInsecure) { getLog().info("Accepting unsecure HTTPS connections."); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustAllStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( sfr); connectionManager.setDefaultMaxPerRoute(100); connectionManager.setMaxTotal(200); connectionManager.setValidateAfterInactivity(1000); HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager) .build(); executor = Executor.newInstance(httpClient); } catch (Exception ex) { throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex); } } else { executor = Executor.newInstance(); } Settings settings = session.getSettings(); if (StringUtils.isNotBlank(serverId)) { Server server = settings.getServer(serverId); if (server == null) { throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml"); } getLog().debug("ServerId: " + serverId); executor.auth(server.getUsername(), server.getPassword()); } Request request = createRequestMethod(); request.setHeader("Accept", accept); if (httpHeaders != null) { for (Entry<String, String> entry : httpHeaders.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (formParams != null) { Form form = Form.form(); for (Entry<String, String> entry : formParams.entrySet()) { form.add(entry.getKey(), entry.getValue()); } } if (fromFile != null) { if (!fromFile.exists()) { throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist."); } if (StringUtils.isBlank(contentType)) { contentType = Files.probeContentType(fromFile.toPath()); } getLog().debug("From file: " + fromFile); getLog().debug("Upload file size: " + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue())); getLog().debug("Content type: " + contentType); if (StringUtils.isBlank(contentType)) { request.body(new FileEntity(fromFile)); } else { request.body(new FileEntity(fromFile, ContentType.create(contentType))); } } getLog().info(method + " " + url); Response response = executor.execute(request); handleResponse(response); } catch (Exception ex) { getLog().error(ex); if (failOnError) { throw new MojoExecutionException(ex.getMessage(), ex); } else { getLog().info("Fail on error is disabled. Continue execution."); } } }
From source file:ai.susi.server.ClientConnection.java
private static PoolingHttpClientConnectionManager getConnctionManager(boolean useAuthentication) { // allow opportunistic encryption if needed boolean trustAllCerts = !"none".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")) && (!useAuthentication || "all".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers"))); Registry<ConnectionSocketFactory> socketFactoryRegistry = null; if (trustAllCerts) { try {/* w ww . j a v a2s . c o m*/ SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier()); socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", trustSelfSignedSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { Log.getLog().warn(e); } } PoolingHttpClientConnectionManager cm = (trustAllCerts && socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry) : new PoolingHttpClientConnectionManager(); // twitter specific options cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost twitter = new HttpHost("twitter.com", 443); cm.setMaxPerRoute(new HttpRoute(twitter), 50); return cm; }
From source file:com.linecorp.armeria.server.SniServerTest.java
public CloseableHttpClient newHttpClient() throws Exception { final SSLContext sslCtx = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true) .build();//from w ww. ja v a 2 s.c om return HttpClients.custom().setDnsResolver(dnsResolver) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslCtx).build(); }
From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java
private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { try {//from w w w. java 2 s. co m HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...) SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true) .build(); httpClientBuilder.setSSLContext(sslContext); // #### ONLY FOR TEST: Do NOT verify hostname SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); httpClientBuilder.setConnectionManager(httpClientConnectionManager); if (getConfig().getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(getConfig().getProperty("http.proxyHost"), Integer.parseInt(getConfig().getProperty("http.proxyPort")))); } httpClient = httpClientBuilder.build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) { throw new RuntimeException(ex); } } return httpClient; }