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

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

Introduction

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

Prototype

public final HttpClientBuilder disableCookieManagement() 

Source Link

Document

Disables state (cookie) management.

Usage

From source file:com.hp.autonomy.hod.client.HodServiceConfigFactory.java

public static HodServiceConfig<EntityType.Application, TokenType.Simple> getHodServiceConfig(
        final TokenProxyService<EntityType.Application, TokenType.Simple> tokenProxyService,
        final Endpoint endpoint) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60000).build());

    final String proxyHost = System.getProperty("hp.hod.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(System.getProperty("hp.hod.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }/*from w  w  w .j ava 2 s.c om*/

    final HodServiceConfig.Builder<EntityType.Application, TokenType.Simple> configBuilder = new HodServiceConfig.Builder<EntityType.Application, TokenType.Simple>(
            endpoint.getUrl()).setHttpClient(builder.build());

    if (tokenProxyService != null) {
        configBuilder.setTokenProxyService(tokenProxyService);
    }

    return configBuilder.build();
}

From source file:basedefense.client.version.ModificationVersionCheck.java

public ModificationVersionCheck() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.disableCookieManagement();
    builder.disableRedirectHandling();/*  w  w  w  .  j  a v  a2s.  c  o  m*/

    builder.setUserAgent(String.format(USER_AGENT_PATTERN, BaseDefenseModification.getInstance().getVersion()));
    builder.setDefaultHeaders(Lists.newArrayList(new BasicHeader("Accept", "application/vnd.github.v3+json")));

    this.httpClient = builder.build();
}

From source file:com.supermap.desktop.icloud.online.AuthenticatorImpl.java

public void setSsoHttpClientBuilder(HttpClientBuilder ssoHttpClientBuilder) {
    this.ssoHttpClientBuilder = ssoHttpClientBuilder.disableCookieManagement().disableRedirectHandling();
}

From source file:com.hp.autonomy.frontend.find.hod.beanconfiguration.HodConfiguration.java

@Bean
public HttpClient httpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    final String proxyHost = environment.getProperty("find.https.proxyHost");

    if (proxyHost != null) {
        final Integer proxyPort = Integer.valueOf(environment.getProperty("find.https.proxyPort", "8080"));
        builder.setProxy(new HttpHost(proxyHost, proxyPort));
    }/*w ww .  j  a  v  a  2s  .co m*/

    builder.disableCookieManagement();

    return builder.build();
}

From source file:org.apache.gobblin.http.ApacheHttpClient.java

public ApacheHttpClient(HttpClientBuilder builder, Config config,
        SharedResourcesBroker<GobblinScopeTypes> broker) {
    super(broker, HttpUtils.createApacheHttpClientLimiterKey(config));
    config = config.withFallback(FALLBACK);

    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(config.getInt(REQUEST_TIME_OUT_MS_KEY))
            .setConnectTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY))
            .setConnectionRequestTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY)).build();

    builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(getHttpConnManager(config));
    client = builder.build();/*  ww w  .  j a v a2  s .co m*/
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static HttpClientBuilder initClientBuilder() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    builder.setConnectionManager(CONNECTION_MANAGER);
    builder.setDefaultRequestConfig(dfltReqConf);

    // UserAgent/*from   w ww.  j  a v  a 2s. com*/
    builder.setUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

    // remove retries; we expect connections to fail; therefore we should not retry
    //builder.disableAutomaticRetries();
    // disable the cookiestore, cause this may cause segfaults and is not needed
    builder.setDefaultCookieStore(null);
    builder.disableCookieManagement();

    // add custom keep alive strategy
    builder.setKeepAliveStrategy(customKeepAliveStrategy());

    // ask for gzip
    builder.addInterceptorLast(new GzipRequestInterceptor());
    // uncompress gzip
    builder.addInterceptorLast(new GzipResponseInterceptor());
    // Proxy
    builder.setRoutePlanner(ProxySettings.RoutePlanner);
    builder.setDefaultCredentialsProvider(ProxySettings.CredsProvider);

    return builder;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
protected void configureClient() {

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {/* w  ww  . java  2 s. com*/

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

protected void configureClient() {

    clientConfig = new DefaultClientConfigImpl();
    clientConfig.loadProperties(getApiName());
    setLoadBalancer(loadBalancer);//from   w  ww  .j  av a  2s  .c  om
    //        clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    //        clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName());
    //        clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName());

    if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) {
        EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName());
        EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + ".");
        DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig);
    }

    loadBalancer.initWithNiwsConfig(clientConfig);

    //        if (HystrixPlugins.getInstance().getMetricsPublisher() == null) {
    //            HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance());
    //        }

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    autoEncodeUri = metadata.isAutoEncodeUri();
    followRedirects = metadata.isFollowRedirects();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanClient.java

/**
 * Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
 * Derived class can configure different http client by overriding this method.
 *
 * @return A closeable http client./*  w w  w .jav  a 2  s . c o m*/
 */
protected CloseableHttpClient getClient() throws AzkabanClientException {
    try {
        // SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
        // Self sign SSL
        SSLContextBuilder sslcb = new SSLContextBuilder();
        sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());

        HttpClientBuilder builder = HttpClientBuilder.create();
        RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(10000)
                .setConnectTimeout(10000).setConnectionRequestTimeout(10000).build();

        builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(new BasicHttpClientConnectionManager()).setSSLSocketFactory(sslsf);

        return builder.build();
    } catch (Exception e) {
        throw new AzkabanClientException("HttpClient cannot be created", e);
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to:/*from w w  w.  j  a  v a  2  s.c om*/
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}