List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:org.georchestra.extractorapp.ws.extractor.csw.CSWExtractor.java
/** * checks the permissions to access to the CSW * //from w ww.j av a 2 s .c o m * @param request * @param username request user name * @param roles * * @throws IOException */ public void checkPermission(ExtractorLayerRequest request, String username, String roles) throws IOException { InputStream content = null; boolean isMetadata = false; try { final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setUserAgent(this.userAgent); HttpClientContext localContext = HttpClientContext.create(); final HttpHost httpHost = new HttpHost(request._isoMetadataURL.getHost(), request._isoMetadataURL.getPort()); HttpGet get = new HttpGet(request._isoMetadataURL.toURI()); if (username != null && (_secureHost.equalsIgnoreCase(request._isoMetadataURL.getHost()) || "127.0.0.1".equalsIgnoreCase(request._isoMetadataURL.getHost()) || "localhost".equalsIgnoreCase(request._isoMetadataURL.getHost()))) { LOG.debug(getClass().getName() + ".checkPermission - Secured Server: adding username header and role headers to request for checkPermission"); WfsExtractor.addImpersonateUserHeaders(username, roles, get); WfsExtractor.enablePreemptiveBasicAuth(request._isoMetadataURL, httpClientBuilder, localContext, httpHost, _adminUserName, _adminPassword); } else { LOG.debug("WcsExtractor.checkPermission - Non Secured Server"); } // checks whether it is a metadata final CloseableHttpClient httpclient = httpClientBuilder.build(); content = httpclient.execute(httpHost, get, localContext).getEntity().getContent(); String metadata = FileUtils.asString(content); Pattern regex = Pattern.compile("<(gmd:)?MD_Metadata*"); isMetadata = regex.matcher(metadata).find(); } catch (Exception e) { throw new IOException(e); } finally { if (content != null) content.close(); } if (!isMetadata) { throw new SecurityException("The metadata is not available: " + request._isoMetadataURL); } }
From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java
public CloseableHttpClient build() { org.apache.http.impl.client.HttpClientBuilder internalHttpClientBuilder = createInternalHttpClientBuilder(); if (useSystemProperties) { internalHttpClientBuilder.useSystemProperties(); }/* w w w .j a v a 2 s . c om*/ if (overrideAllowAnyHostname != null) { if (overrideAllowAnyHostname) { acceptAnyHostname = true; } else { acceptAnyHostname = false; } } if (overrideAllowAnyCertificate != null) { if (overrideAllowAnyCertificate) { acceptAnyCertificate = true; } else { acceptAnyCertificate = false; } } if (acceptAnyCertificate) { internalHttpClientBuilder.setSslcontext(createSslContext()); } if (acceptAnyHostname) { internalHttpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } if (maxConnections > 0) { internalHttpClientBuilder.setMaxConnPerRoute(maxConnections); internalHttpClientBuilder.setMaxConnTotal(maxConnections); } if (requestConfig != null) { internalHttpClientBuilder.setDefaultRequestConfig(requestConfig); } if (!useContentCompression) { internalHttpClientBuilder.disableContentCompression(); } return internalHttpClientBuilder.build(); }
From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java
/** * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ClientCredentials} and optional {@code Proxy} * configuration./*from w ww.j av a 2 s.c o m*/ * @param clientCredentials the Okta account API Key that will be used to authenticate the client with Okta's API sever * @param proxy the HTTP proxy to be used when communicating with the Okta API server (can be null) * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Okta API server. * If null, then SSWS will be used. */ public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy, AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory, Integer connectionTimeout) { Assert.notNull(clientCredentials, "clientCredentials argument is required."); Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number."); RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory : new DefaultRequestAuthenticatorFactory(); this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(); if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) { connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL); } else { connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL); log.warn( "{} ({}) is less than {} ({}). " + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).", MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL, MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE, DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE); } // The connectionTimeout value is specified in seconds in Okta configuration settings. // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds. int connectionTimeoutAsMilliseconds = connectionTimeout * 1000; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds) .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .disableCookieManagement().setDefaultConnectionConfig(connectionConfig) .setConnectionManager(connMgr); this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig); if (proxy != null) { //We have some proxy setting to use! HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort()); httpClientBuilder.setProxy(httpProxyHost); if (proxy.isAuthenticationRequired()) { AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort()); Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider(); credentialsProviderProvider.setCredentials(authScope, credentials); httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider); } } this.httpClient = httpClientBuilder.build(); }
From source file:com.stormpath.sdk.impl.http.httpclient.HttpClientRequestExecutor.java
/** * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ApiKey} and optional {@code Proxy} * configuration.//from w ww. j a v a 2 s .co m * @param clientCredentials the Stormpath account API Key that will be used to authenticate the client with Stormpath's API sever * @param proxy the HTTP proxy to be used when communicating with the Stormpath API server (can be null) * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Stormpath API server. * If null, then Sauthc1 will be used. */ public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy, AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory, Integer connectionTimeout) { Assert.notNull(clientCredentials, "clientCredentials argument is required."); Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number."); RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory : new DefaultRequestAuthenticatorFactory(); this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(); if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) { connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL); } else { connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE); connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL); log.warn( "{} ({}) is less than {} ({}). " + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).", MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL, MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE, DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE); } // The connectionTimeout value is specified in seconds in Stormpath configuration settings. // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds. int connectionTimeoutAsMilliseconds = connectionTimeout * 1000; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds) .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig) .disableCookieManagement().setDefaultConnectionConfig(connectionConfig) .setConnectionManager(connMgr); this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig); if (proxy != null) { //We have some proxy setting to use! HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort()); httpClientBuilder.setProxy(httpProxyHost); if (proxy.isAuthenticationRequired()) { AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort()); Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider(); credentialsProviderProvider.setCredentials(authScope, credentials); httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider); } } this.httpClient = httpClientBuilder.build(); }
From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java
private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { try {/*from w w w.j a v a 2 s. c o 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 (props.getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"), Integer.parseInt(props.getProperty("http.proxyPort")))); } httpClient = httpClientBuilder.build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) { throw new RuntimeException(ex); } } return httpClient; }
From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java
private CloseableHttpClient getHttpClient(URI url) { HttpClientBuilder builder = HttpClientBuilder.create(); ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); builder = builder.setRoutePlanner(routePlanner); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); CredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder.setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); }/*from w w w . j a va 2 s. c o m*/ } } } return builder.build(); }
From source file:org.attribyte.api.http.impl.commons.Commons4Client.java
private void initFromOptions(final ClientOptions options) { if (options != ClientOptions.IMPLEMENTATION_DEFAULT) { HttpClientBuilder builder = HttpClients.custom(); builder.setMaxConnTotal(options.maxConnectionsTotal); builder.setMaxConnPerRoute(options.maxConnectionsPerDestination); builder.setUserAgent(options.userAgent); if (options.proxyHost != null) { builder.setProxy(new HttpHost(options.proxyHost, options.proxyPort)); }//w w w .j a va 2 s .co m this.defaultRequestConfig = RequestConfig.custom().setConnectTimeout(options.connectionTimeoutMillis) .setConnectionRequestTimeout(options.requestTimeoutMillis) .setRedirectsEnabled(RequestOptions.DEFAULT_FOLLOW_REDIRECTS) .setMaxRedirects(RequestOptions.DEFAULT_FOLLOW_REDIRECTS ? 5 : 0) .setAuthenticationEnabled(false).setCircularRedirectsAllowed(false) .setSocketTimeout(options.socketTimeoutMillis).build(); builder.setDefaultRequestConfig(defaultRequestConfig); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize( options.requestBufferSize > options.responseBufferSize ? options.requestBufferSize : options.responseBufferSize) .build(); builder.setDefaultConnectionConfig(connectionConfig); this.httpClient = builder.build(); } else { this.defaultRequestConfig = RequestConfig.DEFAULT; this.httpClient = HttpClients.createDefault(); } }
From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java
public HttpAbstract(String userAgent, boolean bFollowRedirect, ProxyHandler proxyHandler) { HttpClientBuilder builder = HttpClients.custom(); redirectStrategy = new DefaultRedirectStrategy(); if (userAgent != null) { userAgent = userAgent.trim();//from w w w .ja va2s . c o m if (userAgent.length() > 0) builder.setUserAgent(userAgent); else userAgent = null; } if (!bFollowRedirect) builder.disableRedirectHandling(); this.proxyHandler = proxyHandler; Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); credentialsProvider = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(credentialsProvider); cookieStore = new BasicCookieStore(); builder.setDefaultCookieStore(cookieStore); builder.setDefaultCredentialsProvider(credentialsProvider); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); httpClient = builder.build(); }
From source file:com.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java
private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { try {//from w ww. j a v a 2 s . c o 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; }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.AppConfig.java
/** * @return The instance of {@link HttpClient} to be used by {@link ClientHttpRequestFactory} to create client * requests. Pre-configured to support basic authentication using externally configured API user credentials, and to * utilise the API service's support for HTTP response compression (using gzip). *//* ww w. jav a 2 s . c o m*/ @Bean public HttpClient httpClient() { HttpClientBuilder builder = HttpClients.custom(); // Configure the basic authentication credentials to use for all requests CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(this.apiServiceHostName, this.apiServicePort); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.apiUserKey, this.apiUserSecret); credentialsProvider.setCredentials(authScope, credentials); builder.setDefaultCredentialsProvider(credentialsProvider); builder.addInterceptorFirst(new PreemptiveBasicAuthHttpRequestInterceptor()); // Configure default request headers List<Header> headers = new ArrayList<>(5); headers.add(new BasicHeader("Api-Client", SpringApiClientImpl.class.getCanonicalName())); if (this.defaultRequestHeaders != null) { for (String header : this.defaultRequestHeaders) { String[] headerNameAndValue = header.split("==", 2); if (headerNameAndValue.length == 2) { headers.add(new BasicHeader(headerNameAndValue[0], headerNameAndValue[1])); } } } builder.setDefaultHeaders(headers); // HttpClient should by default set the Accept-Encoding request header to indicate the client supports HTTP // response compression using gzip return builder.build(); }