Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients custom.

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:com.ksc.http.apache.client.impl.ApacheHttpClientFactory.java

@Override
public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    final HttpClientConnectionManager cm = cmFactory.create(settings);

    builder.setRequestExecutor(new SdkHttpRequestExecutor())
            .setKeepAliveStrategy(buildKeepAliveStrategy(settings)).disableRedirectHandling()
            .disableAutomaticRetries().setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    // By default http client enables Gzip compression. So we disable it
    // here./*from w  w  w.j a v a 2 s .  c om*/
    // Apache HTTP client removes Content-Length, Content-Encoding and
    // Content-MD5 headers when Gzip compression is enabled. Currently
    // this doesn't affect S3 or Glacier which exposes these headers.
    //
    if (!(settings.useGzip())) {
        builder.disableContentCompression();
    }

    addProxyConfig(builder, settings);

    final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

    if (settings.useReaper()) {
        IdleConnectionReaper.registerConnectionManager(cm);
    }

    return httpClient;
}

From source file:piecework.content.concrete.RemoteContentProvider.java

@PostConstruct
public void init() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);//from   w ww  .j av a 2  s. c  o  m

    this.client = HttpClients.custom().setConnectionManager(cm).build();
}

From source file:org.doxu.g2.gwc.crawler.Crawler.java

public void start() {
    String startUrl = "http://cache.trillinux.org/g2/bazooka.php";
    session.addURL(startUrl);//from  w ww  .  j a  va2 s .  co  m

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Crawler.CONNECT_TIMEOUT)
            .setSocketTimeout(Crawler.CONNECT_TIMEOUT).build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("doxu/" + Crawler.VERSION)
            .setDefaultRequestConfig(requestConfig).disableAutomaticRetries().build()) {
        CrawlerThreadPoolExecutor executor = new CrawlerThreadPoolExecutor(GWC_CRAWLER_THREADS,
                GWC_CRAWLER_THREADS, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
        executor.setListener(new IdleListener() {
            @Override
            public void idle() {
                // If the thread pool is idle and the queue of GWCs to crawl is empty
                // the crawl of GWCs is complete
                if (session.peek() == null) {
                    crawlCompletedBarrier.countDown();
                }
            }
        });

        CrawlThreadFactory factory = CrawlThreadFactory.newFactory(session, httpClient);
        runQueueProcessor(factory, executor);

        executor.shutdown();
        try {
            executor.awaitTermination(30, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex);
    }

    HostChecker hostChecker = new HostChecker(session);
    hostChecker.start();

    printStats();
    System.out.println(session.toXML());
}

From source file:costumetrade.common.util.HttpClientUtils.java

public static InputStream getInputStream(String url) {

    try (CloseableHttpClient httpclient = HttpClients.custom().build();) {
        HttpGet request = new HttpGet(url);
        try (CloseableHttpResponse response = httpclient.execute(request);) {
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("?{}???{}", url, statusCode);
            if (HttpStatus.SC_OK == statusCode) {
                return response.getEntity().getContent();
            }//from w  w  w  .  j  ava2s . c o m
            throw new RuntimeException(String.format("?%s???%s", url, statusCode));
        }
    } catch (IOException e) {
        throw new RuntimeException(String.format("%s", url));
    }
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java

private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate,
        final CustomProxy customProxy) {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.useSystemProperties();
    if (!verifyCertificate) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {/*w w  w  .  j a va  2 s. c o  m*/
            builder.loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build()));
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        }

    }
    if (customProxy != null) {
        Jenkins jenkins = PerfSigUIUtils.getInstance();
        if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) {
            final ProxyConfiguration proxyConfiguration = jenkins.proxy;
            if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) {
                httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port));
                if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                            proxyConfiguration.getUserName(), proxyConfiguration.getUserName());
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfiguration.name, proxyConfiguration.port),
                            usernamePasswordCredentials);
                    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        } else {
            httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort()));
            if (StringUtils.isNotBlank(customProxy.getProxyUser())
                    && StringUtils.isNotBlank(customProxy.getProxyPassword())) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                        customProxy.getProxyUser(), customProxy.getProxyPassword());
                credsProvider.setCredentials(
                        new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()),
                        usernamePasswordCredentials);
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
                httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            }
        }
    }
    return httpClientBuilder;
}

From source file:org.wso2.apim.billing.clients.APIRESTClient.java

public APIRESTClient(String host) {
    // TODO Auto-generated constructor stub
    httpClient = HttpClients.custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();

    loginUrl = host + "/store/site/blocks/user/login/ajax/login.jag";
    getSubsUrl = host + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag";
    appListUrl = host + "/store/site/blocks/application/application-list/ajax/application-list.jag";
    System.out.println("host " + host);
}

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {/*  w  ww.j a va2 s  .c  o  m*/
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.terasology.telemetry.TelemetryEmitter.java

private static HttpClientAdapter getDefaultAdapter(URL url) {

    // Make a new client with custom concurrency rules
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(50);/*from   ww  w .  j a va  2 s. c  om*/

    // Make the client
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();

    // Build the adapter
    return ApacheHttpClientAdapter.builder().url(url.toString()).httpClient(client).build();
}

From source file:de.fraunhofer.iosb.ilt.tests.Constants.java

public static SensorThingsService createService(URL serviceUrl)
        throws MalformedURLException, URISyntaxException {
    SensorThingsService service = new SensorThingsService(serviceUrl);
    if (USE_OPENID_CONNECT) {
        service.setTokenManager(new TokenManagerOpenIDConnect().setTokenServerUrl(TOKEN_SERVER_URL)
                .setClientId(CLIENT_ID).setUserName(USERNAME).setPassword(PASSWORD));
    }//from   w  w w . ja  v a 2 s .c  o m
    if (USE_BASIC_AUTH) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = new URL(BASE_URL);
        credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(USERNAME, PASSWORD));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    }
    return service;
}

From source file:de.perdian.apps.downloader.core.impl.UrlStreamFactory.java

private synchronized HttpEntity ensureHttpEntity() throws IOException {
    if (this.cachedEntity == null) {

        HttpGet httpGet = new HttpGet(this.getUrlSupplier().get().toString());
        httpGet.setHeader("User-Agent", UUID.randomUUID().toString());

        HttpClient httpClient = HttpClients.custom().build();

        HttpResponse httpResponse = httpClient.execute(httpGet);
        this.cachedEntity = httpResponse.getEntity();

    }/*from   ww w .j  a v  a2  s .co m*/
    return this.cachedEntity;
}