Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setDefaultCookieStore()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setDefaultCookieStore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpWebConnection.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Lazily initializes the internal HTTP client.
 *
 * @return the initialized HTTP client
 */
protected HttpClientBuilder getHttpClientBuilder() {
    final Thread currentThread = Thread.currentThread();
    HttpClientBuilder builder = httpClientBuilder_.get(currentThread);
    if (builder == null) {
        builder = createHttpClientBuilder();

        // 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()));
        builder.setUserAgent(webClient_.getBrowserVersion().getUserAgent());
        httpClientBuilder_.put(currentThread, builder);
    }

    return builder;
}
 
Example 2
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 5 votes vote down vote up
/**
 * 获取Http连接
 *
 * @param cookieStore cookie域
 */
private CloseableHttpClient getHttpClient(CookieStore cookieStore) {
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
            .setConnectionManager(pool)
            .setDefaultRequestConfig(requestConfig);
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }else{
        httpClientBuilder.setDefaultCookieStore(baseCookieStore);
    }
    return httpClientBuilder.build();
}
 
Example 3
Source File: SyncHttpClientGenerator.java    From cetty with Apache License 2.0 5 votes vote down vote up
private void reduceCookie(HttpClientBuilder httpClientBuilder, Payload payload) {
    if (payload.isUnsupportedCookie()) {
        httpClientBuilder.disableCookieManagement();
        return;
    }
    httpClientBuilder.setDefaultCookieStore(generatorCookie(payload));
}
 
Example 4
Source File: HttpClientFactory.java    From devops-cm-client with Apache License 2.0 5 votes vote down vote up
CloseableHttpClient createClient() {

        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultCookieStore(cookieStore);
        builder.setDefaultCredentialsProvider(credentialsProvider);
        builder.setUserAgent(format("SAP CM Client/%s based on Olingo v%s",
                getShortVersion(),
                getOlingoV2Version()));
        return builder.build();
    }
 
Example 5
Source File: HttpManager.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
/**
 * 获取Http客户端连接对象
 * @param timeOut 超时时间
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客户端连接对象
 */
public CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 创建Http请求配置参数
    RequestConfig.Builder builder = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 创建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(new RetryHandler())
            // 配置连接池管理对象
            .setConnectionManager(connManager)
            // 302跳转
            .setRedirectStrategy(new RedirectStrategy());

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
Example 6
Source File: Instagram4j.java    From instagram4j with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some variables
 */
public void setup() {
	log.info("Setup...");

	if (StringUtils.isEmpty(this.username)) {
		throw new IllegalArgumentException("Username is mandatory.");
	}

	if (StringUtils.isEmpty(this.password)) {
		throw new IllegalArgumentException("Password is mandatory.");
	}

	this.deviceId = InstagramHashUtil.generateDeviceId(this.username, this.password);

	if (StringUtils.isEmpty(this.uuid)) {
		this.uuid = InstagramGenericUtil.generateUuid(true);
	}

	if (StringUtils.isEmpty(this.advertisingId)) {
		this.advertisingId = InstagramGenericUtil.generateUuid(true);
	}

	if (this.cookieStore == null) {
		this.cookieStore = new BasicCookieStore();
	}

	log.info("Device ID is: " + this.deviceId + ", random id: " + this.uuid);
	HttpClientBuilder builder = HttpClientBuilder.create();
	if (proxy != null) {
		builder.setProxy(proxy);
	}

	if (credentialsProvider != null)
		builder.setDefaultCredentialsProvider(credentialsProvider);

	builder.setDefaultCookieStore(this.cookieStore);
	this.client = builder.build();
}
 
Example 7
Source File: HttpManager.java    From PicCrawler with Apache License 2.0 5 votes vote down vote up
/**
 * 获取Http客户端连接对象
 * @param timeOut 超时时间
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客户端连接对象
 */
private CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 创建Http请求配置参数
    RequestConfig.Builder builder = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 创建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(new RetryHandler())
            // 配置连接池管理对象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
Example 8
Source File: HttpManager.java    From ProxyPool with Apache License 2.0 5 votes vote down vote up
/**
 * 获取Http客户端连接对象
 * @param timeOut 超时时间
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客户端连接对象
 */
public CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 创建Http请求配置参数
    RequestConfig.Builder builder = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 创建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(new RetryHandler())
            // 配置连接池管理对象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
Example 9
Source File: HttpClientFactory.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public IHttpClient buildHttpClient(HttpClientConfig config)
{
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultHeaders(config.createHeaders());
    if (config.hasCookieStore())
    {
        builder.setDefaultCookieStore(config.getCookieStore());
    }
    if (config.hasCredentials())
    {
        AuthScope authScope = config.hasAuthScope() ? config.getAuthScope()
                : ClientBuilderUtils.DEFAULT_AUTH_SCOPE;
        CredentialsProvider credProvider = ClientBuilderUtils.createCredentialsProvider(authScope,
                config.getCredentials());
        builder.setDefaultCredentialsProvider(credProvider);
    }

    sslContextFactory.getSslContext(SSLConnectionSocketFactory.SSL, !config.isSslCertificateCheckEnabled())
            .ifPresent(builder::setSSLContext);

    if (!config.isSslHostnameVerificationEnabled())
    {
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }
    builder.setConnectionManager(config.getConnectionManager());
    builder.setMaxConnTotal(config.getMaxTotalConnections());
    builder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    builder.addInterceptorLast(config.getLastRequestInterceptor());
    builder.addInterceptorLast(config.getLastResponseInterceptor());
    builder.setRedirectStrategy(config.getRedirectStrategy());
    builder.setRetryHandler(config.getHttpRequestRetryHandler());
    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed());
    requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    Optional.ofNullable(config.getCookieSpec()).ifPresent(requestConfigBuilder::setCookieSpec);
    builder.setDefaultRequestConfig(requestConfigBuilder.build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT)
            .setSoTimeout(config.getSocketTimeout())
            .build());
    builder.setDnsResolver(config.getDnsResolver());

    HttpClient httpClient = new HttpClient();
    httpClient.setCloseableHttpClient(builder.build());
    if (config.hasBaseUrl())
    {
        httpClient.setHttpHost(HttpHost.create(config.getBaseUrl()));
    }
    httpClient.setSkipResponseEntity(config.isSkipResponseEntity());
    return httpClient;
}
 
Example 10
Source File: HttpClient.java    From utils with Apache License 2.0 4 votes vote down vote up
protected HttpClient() {
    proxies = new ArrayList<HttpHost>();

    HttpClientBuilder builder = HttpClientBuilder.create();

    SSLContext sslContext;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(0);
        return;
    }

    builder.setSSLContext(sslContext);
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    connMgr.setMaxTotal(500);
    connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
    builder.setConnectionManager(connMgr);

    config = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.DEFAULT)
            .build();
    builder.setDefaultRequestConfig(config);

    cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);
    client = builder.build();

    connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
    soTimeout = DEFAULT_SO_TIMEOUT;
}
 
Example 11
Source File: DefaultHttpClientFactory.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
  final String serviceRole = filterConfig.getInitParameter(PARAMETER_SERVICE_ROLE);
  HttpClientBuilder builder;
  GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
  GatewayServices services = (GatewayServices) filterConfig.getServletContext()
      .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
  if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
    MetricsService metricsService = services.getService(ServiceType.METRICS_SERVICE);
    builder = metricsService.getInstrumented(HttpClientBuilder.class);
  } else {
    builder = HttpClients.custom();
  }

  // Conditionally set a custom SSLContext
  SSLContext sslContext = createSSLContext(services, filterConfig, serviceRole);
  if(sslContext != null) {
    builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext));
  }

  if (Boolean.parseBoolean(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.setDefaultAuthSchemeRegistry(authSchemeRegistry)
        .setDefaultCookieStore(new HadoopAuthCookieStore(gatewayConfig))
        .setDefaultCredentialsProvider(credentialsProvider);
  } else {
    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, serviceRole));

  // See KNOX-1530 for details
  builder.disableContentCompression();

  return builder.build();
}