List of usage examples for org.apache.http.impl.client HttpClientBuilder setRoutePlanner
public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner)
From source file:com.kolich.http.HttpClient4ClosureBuilder.java
public HttpClientBuilder getHttpClientBuilder() { final HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()) .setConnectionManager(getConnectionManager()).setUserAgent(userAgent_); // See http://stackoverflow.com/questions/21818242/with-httpclient-4-3-x-executing-a-httphead-for-a-specific-url-gives-nohttprespo // Also, see https://issues.apache.org/jira/browse/HTTPCLIENT-1464 // This disables the addition of the `Accept-Encoding: gzip,deflate` // header on outgoing requests which seems to confuse some servers. // This is off by default, but can be turned off if desired. if (disableContentCompression_) { builder.disableContentCompression(); }//from ww w . jav a 2s. co m if (disableAutomaticRetries_) { builder.disableAutomaticRetries(); } if (disableAuthCaching_) { builder.disableAuthCaching(); } if (useProxySelector_) { builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } return builder; }
From source file:com.redhat.red.offliner.Main.java
/** * Sets up components needed for the download process, including the {@link ExecutorCompletionService}, * {@link java.util.concurrent.Executor}, {@link org.apache.http.client.HttpClient}, and {@link ArtifactListReader} * instances. If baseUrls were provided on the command line, it will initialize the "global" baseUrls list to that. * Otherwise it will use {@link Options#DEFAULT_REPO_URL} and {@link Options#CENTRAL_REPO_URL} as the default * baseUrls. If specified, configures the HTTP proxy and username/password for authentication. * @throws MalformedURLException In case an invalid {@link URL} is given as a baseUrl. */// ww w . j a va 2 s . com protected void init() throws MalformedURLException { int threads = opts.getThreads(); executorService = Executors.newFixedThreadPool(threads, (final Runnable r) -> { // executorService = Executors.newCachedThreadPool( ( final Runnable r ) -> { final Thread t = new Thread(r); t.setDaemon(true); return t; }); executor = new ExecutorCompletionService<>(executorService); errors = new ConcurrentHashMap<String, Throwable>(); final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(); ccm.setMaxTotal(opts.getConnections()); final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm); final String proxy = opts.getProxy(); String proxyHost = proxy; int proxyPort = 8080; if (proxy != null) { final int portSep = proxy.lastIndexOf(':'); if (portSep > -1) { proxyHost = proxy.substring(0, portSep); proxyPort = Integer.parseInt(proxy.substring(portSep + 1)); } final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)); builder.setRoutePlanner(planner); } client = builder.build(); final CredentialsProvider creds = new BasicCredentialsProvider(); cookieStore = new BasicCookieStore(); baseUrls = opts.getBaseUrls(); if (baseUrls == null) { baseUrls = new ArrayList<>(); } List<String> repoUrls = (baseUrls.isEmpty() ? DEFAULT_URLS : baseUrls); System.out.println("Planning download from:\n " + StringUtils.join(repoUrls, "\n ")); for (String repoUrl : repoUrls) { if (repoUrl != null) { final String user = opts.getUser(); if (user != null) { final URL u = new URL(repoUrl); final AuthScope as = new AuthScope(u.getHost(), UrlUtils.getPort(u)); creds.setCredentials(as, new UsernamePasswordCredentials(user, opts.getPassword())); } } if (proxy != null) { final String proxyUser = opts.getProxyUser(); if (proxyUser != null) { creds.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, opts.getProxyPassword())); } } } artifactListReaders = new ArrayList<>(3); artifactListReaders.add(new FoloReportArtifactListReader()); artifactListReaders.add(new PlaintextArtifactListReader()); artifactListReaders.add(new PomArtifactListReader(opts.getSettingsXml(), opts.getTypeMapping(), creds)); }
From source file:com.hpe.elderberry.TaxiiConnection.java
public RestTemplate getRestTemplate() { if (restTemplate == null) { HttpClientBuilder builder = custom(); if (useProxy) { if ("".equals(proxyHost)) { proxyHost = System.getProperty(discoveryUrl.getScheme() + ".proxyHost"); }//from www . j a v a2 s . c o m if (proxyPort == 0) { proxyPort = Integer.parseInt(System.getProperty(discoveryUrl.getScheme() + ".proxyPort", "0")); } if ("".equals(proxyHost) || proxyHost == null || proxyPort == 0) { log.warn("proxy requested, but not setup, not using a proxy"); } else { log.info("using " + discoveryUrl.getScheme() + " proxy: " + proxyHost + ":" + proxyPort); HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); } } if (getTrustStore() != null || getKeyStore() != null) { SSLContext sslContext; try { sslContext = SSLContexts.custom() .loadTrustMaterial(getTrustStore(), new TrustSelfSignedStrategy()) .loadKeyMaterial(getKeyStore(), keyPassword).build(); } catch (Exception e) { log.error("unable to create SSL context, " + e.getMessage(), e); throw new RuntimeException(e); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); builder.setSSLSocketFactory(sslsf); } if (!"".equals(username)) { restTemplate = new RestTemplate( new PreemptiveAuthHttpRequestFactor(username, password, builder.build())); } else { restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(builder.build())); } if (marshaller == null) { marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan("org.mitre"); try { marshaller.afterPropertiesSet(); } catch (Exception e) { log.error("unable to create Jaxb2 Marshaller: " + e.getMessage(), e); throw new RuntimeException(e); } } MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter(marshaller); converter.setSupportedMediaTypes(singletonList(APPLICATION_XML)); //noinspection unchecked restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter)); } return restTemplate; }
From source file:com.dnanexus.DXHTTPRequest.java
/** * Construct the DXHTTPRequest using the given DXEnvironment. *//*ww w.j av a2 s.c o m*/ public DXHTTPRequest(DXEnvironment env) { this.securityContext = env.getSecurityContextJson(); this.apiserver = env.getApiserverPath(); this.disableRetry = env.isRetryDisabled(); SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } SSLConnectionSocketFactory sslSF = null; try { sslSF = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); String proxyHostS = System.getProperty("https.proxyHost"); String proxyPortS = System.getProperty("https.proxyPort"); if ((proxyHost == null || proxyPort == null) && (proxyHostS == null || proxyPortS == null)) { this.httpclient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); } else { HttpHost proxy = null; if (proxyHostS != null && proxyPortS != null) { proxy = new HttpHost(proxyHostS, Integer.parseInt(proxyPortS)); } else { proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); } httpClientBuilder.setProxy(proxy); HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner).setSSLSocketFactory(sslSF); httpclient = httpClientBuilder.setUserAgent(USER_AGENT).build(); } }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Create a new client (with an explicit proxy and possibly transparent authentication) * //from w ww .j a v a 2 s. c om * @param aIdpUrl * the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP" * @param aUsername * the user name to log into the IdP. * @param aPassword * the password to log in to the IdP. * @param aProxy * if not {@code null}, use this proxy instead of the default system proxy (if any) * @param anyCert * if {@code true}, accept any certificate from any remote host. Otherwise, * certificates need to be installed in the JRE. * @param transparentAuth * if {@code true} (default), add a HttpRequestPostProcessor to transparently * authenticate. Otherwise, you must handle the authentication process yourself. */ public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert, boolean transparentAuth) { setIdpUrl(aIdpUrl); setUsername(aUsername); setPassword(aPassword); // Use a pooling connection manager, because we'll have to do a call out to the IdP // while still being in a connection with the SP PoolingHttpClientConnectionManager connMgr; if (anyCert) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()) .register("https", new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (GeneralSecurityException e) { // There shouldn't be any of these exceptions, because we do not use an actual // keystore throw new IllegalStateException(e); } } else { connMgr = new PoolingHttpClientConnectionManager(); } connMgr.setMaxTotal(10); connMgr.setDefaultMaxPerRoute(5); // The client needs to remember the auth cookie cookieStore = new BasicCookieStore(); RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); // Let's throw all common client elements into one builder object HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr) // The client needs to remember the auth cookie .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore) // Add the ECP/PAOS headers - needs to be added first so the cookie we get from // the authentication can be handled by the RequestAddCookies interceptor later .addInterceptorFirst(new HttpRequestPreprocessor()); // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default) if (transparentAuth) { customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor()); } // Build the client with/without proxy settings if (aProxy == null) { // use the proxy settings of the JVM, if specified client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build(); } else { // use the explicit proxy client = customClient.setProxy(aProxy).build(); } parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); }
From source file:org.commonjava.util.jhttpc.HttpFactory.java
public CloseableHttpClient createClient(final SiteConfig location) throws JHttpCException { CloseableHttpClient client;// w w w .j a va 2s . c om if (location != null) { HttpClientBuilder builder = HttpClients.custom(); if (authenticator != null) { builder = authenticator.decorateClientBuilder(builder); } logger.debug("Using site config: {} for advanced client options", location); SiteConnectionConfig connConfig = new SiteConnectionConfig(location); final SSLConnectionSocketFactory sslFac = createSSLSocketFactory(location); if (sslFac != null) { // HostnameVerifier verifier = new SSLHostnameVerifierImpl( ); // builder.setSSLHostnameVerifier( verifier ); builder.setSSLSocketFactory(sslFac); connConfig.withSSLConnectionSocketFactory(sslFac); } ConnectionManagerTracker managerWrapper = connectionCache.getTrackerFor(connConfig); builder.setConnectionManager(managerWrapper.acquire()); if (location.getProxyHost() != null) { final HttpRoutePlanner planner = new DefaultProxyRoutePlanner( new HttpHost(location.getProxyHost(), getProxyPort(location))); builder.setRoutePlanner(planner); } final int timeout = 1000 * location.getRequestTimeoutSeconds(); builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout).setConnectTimeout(timeout).build()); client = new TrackedHttpClient(builder.build(), managerWrapper); // client = builder.build(); } else { client = HttpClients.createDefault(); } return client; }
From source file:org.rundeck.api.ApiCall.java
/** * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates * * @return an {@link HttpClient} instance - won't be null */// ww w .j a v a 2s. c o m private CloseableHttpClient instantiateHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties(); // configure user-agent httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion()); if (client.isSslHostnameVerifyAllowAll()) { httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } if (client.isSslCertificateTrustAllowSelfSigned()) { // configure SSL try { httpClientBuilder.setSslcontext( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } if (client.isSystemProxyEnabled()) { // configure proxy (use system env : http.proxyHost / http.proxyPort) httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (client.getToken() != null) { request.addHeader(AUTH_TOKEN_HEADER, client.getToken()); //System.out.println("httpClient adding token header"); } else if (client.getSessionID() != null) { request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID()); //System.out.println("httpClient adding session header, sessionID="+client.getSessionID()); } } }); return httpClientBuilder.build(); }