Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java

public HttpClient createHttpClient() {
    HttpClientConnectionManager connManager = pooledConnections ? createPoolingConnectionManager()
            : createBasicConnectionManager();

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore)
            .setUserAgent("Jolokia JMX-Client (using Apache-HttpClient/" + getVersionInfo() + ")")
            .setDefaultRequestConfig(createRequestConfig());

    //        if (user != null && authenticator != null) {
    //            authenticator.authenticate(builder, user, password);
    //        }//from ww w  . j a v a 2  s .  co m

    setupProxyIfNeeded(builder);

    return builder.build();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

protected synchronized HttpClient getHttpClient(final String url) throws DSSException {

    if (httpClient != null) {

        return httpClient;
    } else {//from   www  . j av a2 s.com

        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        httpClientBuilder = configCredentials(httpClientBuilder, url);

        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket)
                .setConnectionRequestTimeout(timeoutConnection).build();
        httpClientBuilder = httpClientBuilder.setDefaultRequestConfig(requestConfig);
        httpClientBuilder.setConnectionManager(getConnectionManager());

        httpClient = httpClientBuilder.build();
        return httpClient;
    }
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        PoolingHttpClientConnectionManager cm;
        if (Context.getInstance().getTrustAllCerts()) {
            try {
                SSLContextBuilder scb = SSLContexts.custom();
                scb.loadTrustMaterial(null, new TrustStrategy() {
                    @Override// w  ww  .  j  a v a  2 s.c o  m
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                });
                SSLContext sslContext = scb.build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                        .<ConnectionSocketFactory>create().register("https", sslsf)
                        .register("http", new PlainConnectionSocketFactory()).build();
                cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            } catch (Exception e) {
                logger.warn("Could not set HttpClient to trust all SSL certificates", e);
                cm = new PoolingHttpClientConnectionManager();
            }
        } else {
            cm = new PoolingHttpClientConnectionManager();
        }
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        HttpHost localhost = new HttpHost("localhost", 80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);
        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm);
        builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        builder.setDefaultCookieStore(new BasicCookieStore());
        httpClient = builder.build();
    }
    return httpClient;
}

From source file:com.fluidops.fedx.FedX.java

protected FedX(Config config, Cache cache, Statistics statistics, EndpointListProvider endpointListProvider,
        SummaryProvider summaryProvider) {
    this.config = config;
    this.cache = cache;
    this.statistics = statistics;
    this.endpointListProvider = endpointListProvider;
    this.summaryProvider = summaryProvider;

    // initialize httpclient parameters
    HttpClientBuilder httpClientBuilder = HttpClientBuilders.getSSLTrustAllHttpClientBuilder();
    httpClientBuilder.setMaxConnTotal(config.getMaxHttpConnectionCount());
    httpClientBuilder.setMaxConnPerRoute(config.getMaxHttpConnectionCountPerRoute());

    //httpClientBuilder.evictExpiredConnections();
    //httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    //httpClientBuilder.setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS);
    //httpClientBuilder.disableAutomaticRetries();

    //      httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy(){
    ///*from w ww. j  av a2  s .c  o m*/
    //          @Override
    //          public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    //              return 0;
    //          }});

    httpClient = httpClientBuilder.build();

    synchronized (log) {
        if (monitoring == null) {
            monitoring = MonitoringFactory.createMonitoring(config);
        }
    }

    executor = Executors.newCachedThreadPool();

    scheduler = new ControlledWorkerScheduler(config.getWorkerThreads(), "Evaluation Scheduler");
    if (log.isDebugEnabled()) {
        log.debug("Scheduler for async operations initialized with " + config.getWorkerThreads()
                + " worker threads.");
    }

    // initialize prefix declarations, if any
    String prefixFile = config.getPrefixDeclarations();
    if (prefixFile != null) {
        prefixDeclarations = new Properties();
        try {
            prefixDeclarations.load(new FileInputStream(new File(prefixFile)));
        } catch (IOException e) {
            throw new FedXRuntimeException("Error loading prefix properties: " + e.getMessage());
        }
    }
    open = true;
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpClient(Settings settings, HttpAuthRegistry httpAuthRegistry, SSLService sslService) {
    super(settings);
    this.httpAuthRegistry = httpAuthRegistry;
    this.defaultConnectionTimeout = HttpSettings.CONNECTION_TIMEOUT.get(settings);
    this.defaultReadTimeout = HttpSettings.READ_TIMEOUT.get(settings);
    this.maxResponseSize = HttpSettings.MAX_HTTP_RESPONSE_SIZE.get(settings);
    this.settingsProxy = getProxyFromSettings();

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // ssl setup/*from   w ww .j  av  a2 s .c  o m*/
    Settings sslSettings = settings.getByPrefix(SETTINGS_SSL_PREFIX);
    boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY)
            .isHostnameVerificationEnabled();
    HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslService.sslSocketFactory(sslSettings), verifier);
    clientBuilder.setSSLSocketFactory(factory);

    clientBuilder.evictExpiredConnections();
    clientBuilder.setMaxConnPerRoute(MAX_CONNECTIONS);
    clientBuilder.setMaxConnTotal(MAX_CONNECTIONS);

    client = clientBuilder.build();
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

private static HttpClient createHttpClient()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ///*from   w ww . j av a2  s.  co  m*/
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    b.setSSLContext(sslContext);
    //b.setSSLHostnameVerifier(new NoopHostnameVerifier());

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    CloseableHttpClient client = b.build();
    return client;
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

public FusionPipelineClient(String endpointUrl, String fusionUser, String fusionPass, String fusionRealm)
        throws MalformedURLException {

    this.fusionUser = fusionUser;
    this.fusionPass = fusionPass;
    this.fusionRealm = fusionRealm;

    String fusionLoginConf = System.getProperty(FusionKrb5HttpClientConfigurer.LOGIN_CONFIG_PROP);
    if (fusionLoginConf != null && !fusionLoginConf.isEmpty()) {
        httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
        isKerberos = true;//from  w w  w. ja v  a  2s  . c om
    } else {
        globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
        cookieStore = new BasicCookieStore();

        // build the HttpClient to be used for all requests
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore);
        httpClientBuilder.setMaxConnPerRoute(100);
        httpClientBuilder.setMaxConnTotal(500);

        if (fusionUser != null && fusionRealm == null)
            httpClientBuilder.addInterceptorFirst(new PreEmptiveBasicAuthenticator(fusionUser, fusionPass));

        httpClient = httpClientBuilder.build();
    }

    originalEndpoints = Arrays.asList(endpointUrl.split(","));
    try {
        sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm);
    } catch (Exception exc) {
        if (exc instanceof RuntimeException) {
            throw (RuntimeException) exc;
        } else {
            throw new RuntimeException(exc);
        }
    }

    random = new Random();
    jsonObjectMapper = new ObjectMapper();

    requestCounter = new AtomicInteger(0);
}

From source file:ee.ria.xroad.proxy.clientproxy.ClientProxy.java

private void createClient() throws Exception {
    log.trace("createClient()");

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);// w  w  w.j  ava 2  s .  c  o m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();

    HttpClientConnectionManager connectionManager = getClientConnectionManager();
    cb.setConnectionManager(connectionManager);

    if (SystemProperties.isClientUseIdleConnectionMonitor()) {
        connectionMonitor = new IdleConnectionMonitorThread(connectionManager);
        connectionMonitor
                .setIntervalMilliseconds(SystemProperties.getClientProxyIdleConnectionMonitorInterval());
        connectionMonitor.setConnectionIdleTimeMilliseconds(
                SystemProperties.getClientProxyIdleConnectionMonitorIdleTime());
    }

    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

protected synchronized HttpClient getHttpClient(final URI uri) throws DSSException {

    if (httpClient != null && !updated) {
        return httpClient;
    }/*from w  ww .  j  a  v a  2 s.c o m*/
    if (LOG.isTraceEnabled() && updated) {
        LOG.trace(">>> Proxy preferences updated");
    }
    final HttpClientBuilder httpClientBuilder = configCredentials(uri);
    final RequestConfig.Builder custom = RequestConfig.custom();
    custom.setSocketTimeout(timeoutSocket);
    custom.setConnectionRequestTimeout(timeoutConnection);
    final RequestConfig requestConfig = custom.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(getConnectionManager());

    httpClient = httpClientBuilder.build();
    return httpClient;
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {/*w  w  w  . j a va  2s .  co  m*/
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}