Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

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

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:io.seldon.external.ExternalPluginServer.java

@Autowired
public ExternalPluginServer(GlobalConfigHandler globalConfigHandler) {
    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(150);/*from w  w  w  .  j  a  v a 2s  . co m*/
    cm.setDefaultMaxPerRoute(150);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();
    globalConfigHandler.addSubscriber(ZK_CONFIG_TEMP, this);
}

From source file:org.ops4j.pax.web.itest.DigestAuthenticationTest.java

@Test
public void shouldPermitAccess() throws Exception {
    assertThat(servletContext.getContextPath(), is("/digest"));

    String path = String.format("http://localhost:%d/digest/hello", getHttpPort());
    HttpClientContext context = HttpClientContext.create();
    BasicCredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("mustermann", "mustermann"));
    CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(cp).build();

    HttpGet httpGet = new HttpGet(path);
    HttpResponse response = client.execute(httpGet, context);

    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, is(200));//www.  j av  a  2 s . com
    String text = EntityUtils.toString(response.getEntity());
    assertThat(text, containsString("Hello from Pax Web!"));
}

From source file:org.fcrepo.camel.FedoraClient.java

/**
 * Create a FedoraClient with a set of authentication values.
 *//*  w w  w .  j  a  v  a 2  s .c o  m*/
public FedoraClient(final String username, final String password, final String host,
        final Boolean throwExceptionOnFailure) {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = null;

    this.throwExceptionOnFailure = throwExceptionOnFailure;

    if ((username == null || username.isEmpty()) || (password == null || password.isEmpty())) {
        this.httpclient = HttpClients.createDefault();
    } else {
        if (host != null) {
            scope = new AuthScope(new HttpHost(host));
        }
        credsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
        this.httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
}

From source file:com.redhat.developers.msa.hello.HelloResource.java

/**
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a REST endpoint with
 * Hystrix fallback support./*from  w  w  w.  ja v a  2s  .  c  o m*/
 *
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
private NamasteService getNextService() {
    final String serviceName = "namaste";
    // This stores the Original/Parent ServerSpan from ZiPkin.
    final ServerSpan serverSpan = brave.serverSpanThreadBinder().getCurrentServerSpan();
    final CloseableHttpClient httpclient = HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(brave.clientRequestInterceptor(),
                    new DefaultSpanNameProvider()))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(brave.clientResponseInterceptor())).build();
    String url = String.format("http://%s:8080/", serviceName);
    return HystrixFeign.builder()
            // Use apache HttpClient which contains the ZipKin Interceptors
            .client(new ApacheHttpClient(httpclient))
            // Bind Zipkin Server Span to Feign Thread
            .requestInterceptor((t) -> brave.serverSpanThreadBinder().setCurrentSpan(serverSpan))
            .logger(new Logger.ErrorLogger()).logLevel(Level.BASIC).decoder(new JacksonDecoder())
            .target(NamasteService.class, url, () -> Collections.singletonList("Namaste response (fallback)"));
}

From source file:org.apache.manifoldcf.jettyrunner.ManifoldCFJettyShutdown.java

public void shutdownJetty() throws Exception {
    // Pick up shutdown token
    String shutdownToken = System.getProperty("org.apache.manifoldcf.jettyshutdowntoken");
    if (shutdownToken != null) {
        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(false)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        HttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy()).build();

        HttpPost method = new HttpPost(
                jettyBaseURL + "/shutdown?token=" + URLEncoder.encode(shutdownToken, "UTF-8"));
        method.setEntity(new StringEntity("", ContentType.create("text/plain", StandardCharsets.UTF_8)));
        try {//from  w ww  .j a v a2  s. c  o m
            HttpResponse httpResponse = httpClient.execute(method);
            int resultCode = httpResponse.getStatusLine().getStatusCode();
            if (resultCode != 200)
                throw new Exception("Received result code " + resultCode + " from POST");
        } catch (org.apache.http.NoHttpResponseException e) {
            // This is ok and expected
        }
    } else {
        throw new Exception("No jetty shutdown token specified");
    }
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectTimeout())
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true)
                .setProxy(myProxy).build();

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }//from   w w w.jav a2  s.  c o m

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:com.linkedin.multitenant.db.ProxyDatabase.java

public ProxyDatabase() {
    RequestConfig rq = RequestConfig.custom().setStaleConnectionCheckEnabled(false).build();

    m_client = HttpClients.custom().setDefaultRequestConfig(rq).setMaxConnTotal(200).build();
    m_handler = new MyResponseHandler();
}

From source file:com.vmware.content.samples.client.util.HttpUtil.java

private static CloseableHttpClient getCloseableHttpClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:com.ccreanga.bitbucket.rest.client.http.BitBucketHttpExecutor.java

public BitBucketHttpExecutor(String baseUrl, BitBucketCredentials credentials) {
    this.baseUrl = baseUrl;

    HttpHost targetHost = HttpHost.create(baseUrl);
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(5);//from w  ww . j a  va2  s .  c o  m
    connectionManager.setDefaultMaxPerRoute(4);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    httpClient = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}