List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCookieStore
public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore)
From source file:com.normalexception.app.rx8club.html.LoginFactory.java
/** * Initialize the client, cookie store, and context *///from w w w. java 2 s.c o m private void initializeClientInformation() { Log.d(TAG, "Initializing Client..."); /* Log.d(TAG, "Creating Custom Cache Configuration"); CacheConfig cacheConfig = CacheConfig.custom() .setMaxCacheEntries(1000) .setMaxObjectSize(8192) .build(); */ Log.d(TAG, "Creating Custom Request Configuration"); RequestConfig rConfig = RequestConfig.custom().setCircularRedirectsAllowed(true) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); cookieStore = new BasicCookieStore(); httpContext = new BasicHttpContext(); Log.d(TAG, "Building Custom HTTP Client"); HttpClientBuilder httpclientbuilder = HttpClients.custom(); //httpclientbuilder.setCacheConfig(cacheConfig); httpclientbuilder.setDefaultRequestConfig(rConfig); httpclientbuilder.setDefaultCookieStore(cookieStore); Log.d(TAG, "Connection Manager Initializing"); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); httpclientbuilder.setConnectionManager(cm); Log.d(TAG, "Enable GZIP Compression"); httpclientbuilder.addInterceptorLast(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpclientbuilder.addInterceptorLast(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); // Follow Redirects Log.d(TAG, "Registering Redirect Strategy"); httpclientbuilder.setRedirectStrategy(new RedirectStrategy()); // Setup retry handler Log.d(TAG, "Registering Retry Handler"); httpclientbuilder.setRetryHandler(new RetryHandler()); // Setup KAS Log.d(TAG, "Registering Keep Alive Strategy"); httpclientbuilder.setKeepAliveStrategy(new KeepAliveStrategy()); httpclient = httpclientbuilder.build(); //httpclient.log.enableDebug( // MainApplication.isHttpClientLogEnabled()); isInitialized = true; }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare connection/* w w w. j av a 2s. c o m*/ * * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception */ @Override public void prepareConnection() throws EWSHttpException { try { HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); if (getProxy() != null) { HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort()); builder.setProxy(proxy); if (HttpProxyCredentials.isProxySet()) { NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(), HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxy), cred); builder.setDefaultCredentialsProvider(credsProvider); } } if (getUserName() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); } //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setAuthenticationEnabled(true); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setRedirectsEnabled(isAllowAutoRedirect()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials if (getUserName() != null) { ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); } // builder.setDefaultRequestConfig(rcBuilder.build()); httpPostReq = new HttpPost(getUrl().toString()); httpPostReq.addHeader("Content-type", getContentType()); //httpPostReq.setDoAuthentication(true); httpPostReq.addHeader("User-Agent", getUserAgent()); httpPostReq.addHeader("Accept", getAccept()); httpPostReq.addHeader("Keep-Alive", "300"); httpPostReq.addHeader("Connection", "Keep-Alive"); if (isAcceptGzipEncoding()) { httpPostReq.addHeader("Accept-Encoding", "gzip,deflate"); } if (getHeaders().size() > 0) { for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) { httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue()); } } //create the client client = builder.build(); } catch (Exception er) { er.printStackTrace(); } }
From source file:leap.webunit.client.THttpClientImpl.java
protected HttpClient createDefaultHttpClient() { HttpClientBuilder cb = HttpClientBuilder.create(); //TODO : small buffer size will cause socket closed when reading response entity? PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry(), this.dnsResolver); //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build()); cb.setConnectionManager(cm);//from w ww. ja v a 2 s.c o m cb.setDefaultCookieStore(this.cookieStore); cb.setRedirectStrategy(new DefaultRedirectStrategy() { @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { if (!autoRedirect) { return false; } return super.isRedirected(request, response, context); } }); return cb.build(); }
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 w w.j av a 2s . 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:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare asynchronous connection./*from w w w . java2 s .c o m*/ * * @throws microsoft.exchange.webservices.data.EWSHttpException throws EWSHttpException */ public void prepareAsyncConnection() throws EWSHttpException { try { //ssl config HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); builder.setSchemePortResolver(new DefaultSchemePortResolver()); EwsSSLProtocolSocketFactory factory = EwsSSLProtocolSocketFactory.build(trustManger); builder.setSSLSocketFactory(factory); builder.setSslcontext(factory.getContext()); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); // builder.setDefaultRequestConfig(rcBuilder.build()); //HttpClientParams.setRedirecting(client.getParams(), isAllowAutoRedirect()); by default it follows redirects //create the client and execute requests client = builder.build(); httpPostReq = new HttpPost(getUrl().toString()); response = client.execute(httpPostReq); } catch (IOException e) { client = null; httpPostReq = null; throw new EWSHttpException("Unable to open connection to " + this.getUrl()); } catch (Exception e) { client = null; httpPostReq = null; e.printStackTrace(); throw new EWSHttpException("SSL problem " + this.getUrl()); } }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the cookies to the builder based on the request cookies * /* w w w.ja v a 2 s . c o m*/ * @param requestConfigurationBuilder The request builder * @param httpClientBuilder The request builder * @param list The cookies * @param urlHost The URL host */ private void setCookies(final Builder requestConfigurationBuilder, final HttpClientBuilder httpClientBuilder, final List<HttpCookie> list, final String urlHost) { final CookieStore cookieStore = new BasicCookieStore(); final List<HttpCookie> cookies = list; for (final HttpCookie cookie : cookies) { final BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue()); c.setPath("/"); c.setVersion(0); c.setDomain(urlHost); cookieStore.addCookie(c); } httpClientBuilder.setDefaultCookieStore(cookieStore); requestConfigurationBuilder.setCookieSpec(CookieSpecs.BEST_MATCH); }
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 ww w .j ava 2s . 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.gargoylesoftware.htmlunit.HttpWebConnection.java
/** * Lazily initializes the internal HTTP client. * * @return the initialized HTTP client/*from w w w. j av a2 s .co m*/ */ protected HttpClientBuilder getHttpClientBuilder() { HttpClientBuilder builder = httpClientBuilder_.get(); if (builder == null) { builder = createHttpClient(); // this factory is required later // to be sure this is done, we do it outside the createHttpClient() call final RegistryBuilder<CookieSpecProvider> registeryBuilder = RegistryBuilder .<CookieSpecProvider>create().register(HACKED_COOKIE_POLICY, htmlUnitCookieSpecProvider_); builder.setDefaultCookieSpecRegistry(registeryBuilder.build()); builder.setDefaultCookieStore(new HtmlUnitCookieStore(webClient_.getCookieManager())); httpClientBuilder_.set(builder); } return builder; }
From source file:org.apache.hadoop.gateway.dispatch.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(FilterConfig filterConfig) { HttpClientBuilder builder = null; GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext() .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE); if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) { GatewayServices services = (GatewayServices) filterConfig.getServletContext() .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE); MetricsService metricsService = services.getService(GatewayServices.METRICS_SERVICE); builder = metricsService.getInstrumented(HttpClientBuilder.class); } else {//from w w w .j a v a 2 s. c o m builder = HttpClients.custom(); } if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials()); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)).build(); builder = builder.setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCookieStore(new HadoopAuthCookieStore()) .setDefaultCredentialsProvider(credentialsProvider); } else { builder = builder.setDefaultCookieStore(new NoCookieStore()); } builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE); builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE); builder.setRedirectStrategy(new NeverRedirectStrategy()); builder.setRetryHandler(new NeverRetryHandler()); int maxConnections = getMaxConnections(filterConfig); builder.setMaxConnTotal(maxConnections); builder.setMaxConnPerRoute(maxConnections); builder.setDefaultRequestConfig(getRequestConfig(filterConfig)); HttpClient client = builder.build(); return client; }