Java Code Examples for org.apache.http.ssl.SSLContexts#createSystemDefault()

The following examples show how to use org.apache.http.ssl.SSLContexts#createSystemDefault() . 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: HttpSyncClient.java    From Almost-Famous with MIT License 4 votes vote down vote up
public CloseableHttpClient createSyncClient(boolean proxy)
        throws Exception {

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory();
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom()
            .setTcpNoDelay(true)
            .build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
    // Validate connections after 1 sec of inactivity
    connManager.setValidateAfterInactivity(1000);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom()
            .setMaxHeaderCount(200)
            .setMaxLineLength(2000)
            .build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints)
            .build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(poolSize);
    if (maxPerRoute > 0) {
        connManager.setDefaultMaxPerRoute(maxPerRoute);
    } else {
        connManager.setDefaultMaxPerRoute(10);
    }

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    return httpclient;
}
 
Example 2
Source File: FDSHttpClient.java    From galaxy-fds-sdk-java with Apache License 2.0 4 votes vote down vote up
private HttpClient createHttpClient(FDSClientConfiguration config) {
  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs());

  String proxyHost = config.getProxyHost();

  int proxyPort = config.getProxyPort();

  if (proxyHost != null && proxyPort > 0) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    requestConfigBuilder.setProxy(proxy);

    String proxyUsername = config.getProxyUsername();
    String proxyPassword = config.getProxyPassword();
    String proxyDomain = config.getProxyDomain();
    String proxyWorkstation = config.getProxyWorkstation();
    if (proxyUsername != null && proxyPassword != null) {
      credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
          new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));

      authCache = new BasicAuthCache();
      authCache.put(proxy, new BasicScheme());
    }
  }

  RequestConfig requestConfig = requestConfigBuilder.build();

  SocketConfig socketConfig = SocketConfig.custom()
      .setSoTimeout(config.getSocketTimeoutMs())
      .build();

  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  registryBuilder.register("http", new ConnectionInfoRecorderSocketFactory(
      new PlainConnectionSocketFactory()));

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionInfoRecorderSocketFactory(
        sslContext,
        NoopHostnameVerifier.INSTANCE);
    registryBuilder.register("https", sslConnectionSocketFactory);
  }
  ipBlackList = new TimeBasedIpAddressBlackList(config.getIpAddressNegativeDurationMillsec());
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build(),
      null,
      null,
      new RoundRobinDNSResolver(new InternalSiteBlackListDNSResolver(ipBlackList,
          this.dnsResolver == null ?
              SystemDefaultDnsResolver.INSTANCE : this.dnsResolver)),
      config.getHTTPKeepAliveTimeoutMS(), TimeUnit.MILLISECONDS);
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());
  connectionManager.setDefaultSocketConfig(socketConfig);
  FDSBlackListEnabledHostChecker fdsBlackListEnabledHostChecker =
      new FDSBlackListEnabledHostChecker();
  retryHandler = new InternalIpBlackListRetryHandler(config.getRetryCount(),
      ipBlackList, fdsBlackListEnabledHostChecker);

  return HttpClients.custom()
      .setRetryHandler(retryHandler)
      .setServiceUnavailableRetryStrategy(new ServiceUnavailableDNSBlackListStrategy(
          config.getRetryCount(),
          config.getRetryIntervalMilliSec(),
          ipBlackList,
          fdsBlackListEnabledHostChecker))
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .build();
}