Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:com.supermap.desktop.icloud.online.AuthenticatorImpl.java

/**
 * ??HttpClientLicenseServece???HttpClient
 *
 * @param token         ?/*from   ww  w  . ja v  a2s .  c o m*/
 * @param clientBuilder HttpClient
 * @param service
 * @return
 * @throws AuthenticationException
 */
public CloseableHttpClient authenticate(UsernamePassword token, HttpClientBuilder clientBuilder, URL service)
        throws AuthenticationException {
    CloseableHttpClient client = this.ssoHttpClientBuilder.build();
    try {
        String jSessionId = login(client, token, service);
        if (null == jSessionId) {
            return null;
        }
        clientBuilder.addInterceptorLast(new SessionIdCookie(jSessionId));
        return clientBuilder.build();
    } catch (IOException e) {
        throw new AuthenticationException(e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.buffalokiwi.api.APIHttpClient.java

/**
 * Build the http client.  /*w ww.  j a v a 2s.  c  o m*/
 * 
 * @param builder The client builder 
 * @return The built client 
 */
protected CloseableHttpClient buildClient(final HttpClientBuilder builder) {
    return builder.build();
}

From source file:org.eclipse.microprofile.health.tck.SimpleHttp.java

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

    StringBuilder content = new StringBuilder();
    int code;//from   ww w  . j  a va2  s  .co  m

    try {

        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!followRedirects) {
            builder.disableRedirectHandling();
        }

        if (useAuth) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = builder.build();

        HttpResponse response = client.execute(new HttpGet(theUrl));
        code = response.getStatusLine().getStatusCode();

        if (response.getEntity() != null) {

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            String line;

            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return new Response(code, content.toString());
}

From source file:com.northernwall.hadrian.Main.java

private void startHttpClient() {
    try {// w w  w  . ja  va 2 s . co  m
        int maxConnections = Integer.parseInt(properties.getProperty("http.maxConnections", "100"));
        int maxPerRoute = Integer.parseInt(properties.getProperty("http.maxPerRoute", "10"));
        int socketTimeout = Integer.parseInt(properties.getProperty("http.socketTimeout", "1000"));
        int connectionTimeout = Integer.parseInt(properties.getProperty("http.connectionTimeout", "1000"));

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create();
        Registry<ConnectionSocketFactory> registry = registryBuilder
                .register("http", PlainConnectionSocketFactory.INSTANCE).build();

        PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxPerRoute);

        HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(ccm)
                .setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.UTF_8).build())
                .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(socketTimeout)
                        .setConnectTimeout(connectionTimeout).build());
        client = clientBuilder.build();
    } catch (NumberFormatException nfe) {
        throw new IllegalStateException("Error Creating HTTPClient, could not parse property");
    } catch (Exception e) {
        throw new IllegalStateException("Error Creating HTTPClient: ", e);
    }
}

From source file:org.miloss.fgsms.presentation.StatusHelper.java

/**
 * determines if an fgsms service is currently accessible. not for use
 * with other services./*  w  w w .  ja  va 2  s  .  c om*/
 *
 * @param endpoint
 * @return
 */
public String sendGetRequest(String endpoint) {
    //   String result = null;
    if (endpoint.startsWith("http")) {
        // Send a GET request to the servlet
        try {

            URL url = new URL(endpoint);
            int port = url.getPort();
            if (port <= 0) {
                if (endpoint.startsWith("https:")) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            HttpClientBuilder create = HttpClients.custom();

            if (mode == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(url.getHost(), port),
                        new UsernamePasswordCredentials(username, Utility.DE(password)));
                create.setDefaultCredentialsProvider(credsProvider);
                ;

            }
            CloseableHttpClient c = create.build();

            CloseableHttpResponse response = c.execute(new HttpHost(url.getHost(), port),
                    new HttpGet(endpoint));

            c.close();
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                return "OK";
            }
            return String.valueOf(status);

        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.WARN,
                    "error fetching http doc from " + endpoint + ex.getLocalizedMessage());
            return "offline";
        }
    } else {
        return "undeterminable";
    }
}

From source file:es.auth.plugin.AbstractUnitTest.java

protected final JestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();
    // Construct a new Jest client according to configuration via factory
    final JestClientFactory factory1 = new JestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final JestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);//w  ww .  j  a v a 2s  . co m
    return c;
}

From source file:com.smartling.api.sdk.util.HttpProxyUtils.java

/**
 * Get an HttpClient given a proxy config if any
 * @param proxyConfiguration configuration of proxy to use
 * @return org.apache.http.impl.client.CloseableHttpClient
 *//*from  ww w.  ja v a2s .  co  m*/
public CloseableHttpClient getHttpClient(final ProxyConfiguration proxyConfiguration) {
    HttpClientBuilder httpClientBuilder = getHttpClientBuilder();

    if (proxyAuthenticationRequired(proxyConfiguration)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(proxyConfiguration.getHost(), proxyConfiguration.getPort()),
                new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                        proxyConfiguration.getPassword()));

        httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    return httpClientBuilder.build();
}

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

@SuppressWarnings("deprecation")
public static CloseableHttpClient makeHttpClient4(boolean usePool) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setDefaultRequestConfig(
            RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build());

    if (usePool) {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

        int maxTotalConnections = 100;
        try {/*from  w ww .j a v  a 2 s  .  com*/
            maxTotalConnections = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_TOTAL_CONNECTIONS))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine.warn("Unable to retrieve the max number of connections; defaults to 100.");
        }

        int maxConnectionsPerHost = 50;
        try {
            maxConnectionsPerHost = new Integer(
                    EnginePropertiesManager.getProperty(PropertyName.HTTP_CLIENT_MAX_CONNECTIONS_PER_HOST))
                            .intValue();
        } catch (NumberFormatException e) {
            Engine.logEngine
                    .warn("Unable to retrieve the max number of connections per host; defaults to 100.");
        }

        connManager.setDefaultMaxPerRoute(maxConnectionsPerHost);
        connManager.setMaxTotal(maxTotalConnections);

        httpClientBuilder.setConnectionManager(connManager);
    }

    return httpClientBuilder.build();
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

@Test
public void testContentStreamRedirect() throws Exception {
    useDummyCmisBlobProvider();/*from  www .  j a va  2 s  .  co m*/
    setUpData();
    session.clear(); // clear cache

    assumeTrue(isAtomPub || isBrowser);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setRedirectStrategy(NeverRedirectStrategy.INSTANCE); // to check Location header manually
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        String uri = getURI("/testfolder1/testfile1") + "&testredirect=true"; // to provoke a redirect in our dummy blob provider
        HttpGet request = new HttpGet(uri);
        request.setHeader("Authorization", BASIC_AUTH);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
            Header locationHeader = response.getFirstHeader("Location");
            assertNotNull(locationHeader);
            assertEquals("http://example.com/dummyedirect", locationHeader.getValue());
        }
    }
}