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

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#useSystemProperties() . 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: KeySetRetriever.java    From deprecated-security-advanced-modules with Apache License 2.0 7 votes vote down vote up
private CloseableHttpClient createHttpClient(HttpCacheStorage httpCacheStorage) {
	HttpClientBuilder builder;

	if (httpCacheStorage != null) {
		builder = CachingHttpClients.custom().setCacheConfig(cacheConfig).setHttpCacheStorage(httpCacheStorage);
	} else {
		builder = HttpClients.custom();
	}

	builder.useSystemProperties();

	if (sslConfig != null) {
		builder.setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory());
	}

	return builder.build();
}
 
Example 2
Source File: HttpSettings.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link HttpClientBuilder} considering current settings.
 * 
 * @return a {@link HttpClientBuilder} considering current settings.
 */
public HttpClientBuilder createHttpClientBuilder() {
	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	if (getHttpProxy() != null
			&& StringUtils.isNotBlank(getHttpProxy().getHost())) {
		httpClientBuilder = httpClientBuilder.setProxy(new HttpHost(
				getHttpProxy().getHost(), getHttpProxy().getPort(),
				getHttpProxy().getSchema()));
		if (StringUtils.isNotBlank(getHttpProxy().getUser())) {
			Credentials credentials = new UsernamePasswordCredentials(
					getHttpProxy().getUser(), getHttpProxy().getPassword());
			AuthScope authScope = new AuthScope(getHttpProxy().getHost(),
					getHttpProxy().getPort());
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(authScope, credentials);
			httpClientBuilder = httpClientBuilder
					.setDefaultCredentialsProvider(credsProvider);
			httpClientBuilder.useSystemProperties();
		}
	}
	return httpClientBuilder;
}
 
Example 3
Source File: HttpGetter.java    From commafeed with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpClient newClient(int timeout) {
	HttpClientBuilder builder = HttpClients.custom();
	builder.useSystemProperties();
	builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING);
	builder.disableAutomaticRetries();

	builder.setSSLContext(SSL_CONTEXT);
	builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

	RequestConfig.Builder configBuilder = RequestConfig.custom();
	configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
	configBuilder.setSocketTimeout(timeout);
	configBuilder.setConnectTimeout(timeout);
	configBuilder.setConnectionRequestTimeout(timeout);
	builder.setDefaultRequestConfig(configBuilder.build());

	builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build());

	return builder.build();
}
 
Example 4
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void configClient(HttpClientBuilder cb, Map<Prop, Object> settings) throws HTTPException {
  cb.useSystemProperties();
  String agent = (String) settings.get(Prop.USER_AGENT);
  if (agent != null)
    cb.setUserAgent(agent);
  session.setInterceptors(cb);
  session.setContentDecoderRegistry(cb);
  session.setClientManager(cb, this);
  session.setRetryHandler(cb);
}
 
Example 5
Source File: CmmnHttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HttpActivityExecutor createHttpActivityExecutor() {
    HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // client builder settings
    if (config.isUseSystemProperties()) {
        httpClientBuilder.useSystemProperties();
    }

    return new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator(),
            CommandContextUtil.getCmmnEngineConfiguration().getObjectMapper());
}
 
Example 6
Source File: HttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HttpActivityExecutor createHttpActivityExecutor() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // client builder settings
    if (config.isUseSystemProperties()) {
        httpClientBuilder.useSystemProperties();
    }

    return new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator(),
            CommandContextUtil.getProcessEngineConfiguration().getObjectMapper());
}
 
Example 7
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    RequestConfig.Builder requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
            .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
    client.setDefaultRequestConfig(requestConfig.build());

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
    }

    return client;
}
 
Example 8
Source File: GoAgentServerHttpClientBuilder.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();
    builder
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setTcpNoDelay(true)
                    .setSoKeepAlive(true)
                    .build()
            )
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    KeyStore keystore = agentKeystore();

    if (keystore != null) {
        sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
 
Example 9
Source File: APIClient.java    From algoliasearch-client-java with MIT License 5 votes vote down vote up
/**
 * Algolia Search initialization
 *
 * @param applicationID   the application ID you have in your admin interface
 * @param apiKey          a valid API key for the service
 * @param buildHostsArray the list of hosts that you have received for the service
 * @param queryHostsArray the list of hosts that you have received for the service
 */
public APIClient(String applicationID, String apiKey, List<String> buildHostsArray, List<String> queryHostsArray) {
  userAgent = "Algolia for Java (" + version + "); JVM (" + System.getProperty("java.version") + ")";
  verbose = System.getenv("VERBOSE") != null;
  forwardRateLimitAPIKey = forwardAdminAPIKey = forwardEndUserIP = null;
  if (applicationID == null || applicationID.length() == 0) {
    throw new RuntimeException("AlgoliaSearch requires an applicationID.");
  }
  this.applicationID = applicationID;
  if (apiKey == null || apiKey.length() == 0) {
    throw new RuntimeException("AlgoliaSearch requires an apiKey.");
  }
  this.apiKey = apiKey;
  if (buildHostsArray == null || buildHostsArray.size() == 0 || queryHostsArray == null || queryHostsArray.size() == 0) {
    throw new RuntimeException("AlgoliaSearch requires a list of hostnames.");
  }

  this.buildHostsArray = new ArrayList<String>(buildHostsArray);
  this.queryHostsArray = new ArrayList<String>(queryHostsArray);

  HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries();
  //If we are on AppEngine don't use system properties
  if (System.getProperty("com.google.appengine.runtime.version") == null) {
    builder = builder.useSystemProperties();
  }
  this.httpClient = builder.build();
  this.headers = new HashMap<String, String>();
}
 
Example 10
Source File: SamlHTTPMetadataResolver.java    From deprecated-security-advanced-modules with Apache License 2.0 3 votes vote down vote up
private static HttpClient createHttpClient0(Settings settings, Path configPath) throws Exception {

        HttpClientBuilder builder = HttpClients.custom();

        builder.useSystemProperties();

        SettingsBasedSSLConfigurator.SSLConfig sslConfig = getSSLConfig(settings, configPath);

        if (sslConfig != null) {
            builder.setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory());
        }

        return builder.build();
    }