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:org.sonatype.nexus.internal.httpclient.HttpClientManagerImplIT.java

private void testPrepareHttpClientBuilderHttpRequest(boolean isSSL, boolean isProxy) throws Exception {
    // Setup/*from w w w  .j  a v  a2  s . c om*/
    HttpClientBuilder builder = underTest.prepare(plan -> plan.setUserAgentBase(EXPECTED_USER_AGENT));
    builder.setConnectionManager(null);
    if (isProxy) {
        builder.setProxy(new HttpHost(proxyServer.getHostName(), proxyServer.getPort()));
    }
    if (isSSL) {
        setSSL(builder);
    }

    String url;
    if (isSSL) {
        url = "https://" + targetServerSSL.getUrl().getHost() + ":" + targetServerSSL.getPort();
    } else {
        url = "http://" + targetServer.getUrl().getHost() + ":" + targetServer.getPort();
    }

    CloseableHttpResponse resp = null;
    // Execute
    try (CloseableHttpClient client = builder.build()) {
        resp = client.execute(new HttpGet(new URI(url)));
    } finally {
        if (resp != null) {
            resp.close();
        }
    }

    // Verify
    assertThat(resp.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK));
    if (isSSL) {
        assertThat(httpsValidatingBehaviour.getSuccessCount(), equalTo(1));
    } else {
        assertThat(httpValidatingBehaviour.getSuccessCount(), equalTo(1));
    }
    if (isProxy) {
        if (isSSL) {
            // Only one filterable request in SSL (CONNECT) without using MITM
            assertThat(proxyServer.getSuccessCount(), equalTo(1));
        } else {
            // Two filterable requests in non-SSL (initiate and real request)
            assertThat(proxyServer.getSuccessCount(), equalTo(2));
        }
    }
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create http client based on connection manager.
 *
 * @param connectionManager The connection manager setting http client.
 * @return Http client based on connection manager.
 *//*from   w w w .j  a  va  2s  .  c o  m*/
private CloseableHttpClient createHttpClient(HttpClientConnectionManager connectionManager) {
    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
            .disableAutomaticRetries();

    int socketBufferSizeInBytes = this.config.getSocketBufferSizeInBytes();
    if (socketBufferSizeInBytes > 0) {
        builder.setDefaultConnectionConfig(
                ConnectionConfig.custom().setBufferSize(socketBufferSizeInBytes).build());
    }

    return builder.build();
}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

/**
 * Create http client/* w w w.  j  a  v  a 2 s.com*/
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (props.getProperty("proxyHost") != null) {
            httpClientBuilder.setProxy(new HttpHost(props.getProperty("proxyHost"),
                    Integer.parseInt(props.getProperty("proxyPort"))));
        }

        if (props.getProperty("proxyUser") != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                    props.getProperty("proxyUser"), props.getProperty("proxyPwd")));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        httpClient = httpClientBuilder.build();
    }

    return httpClient;
}

From source file:org.hawk.http.HTTPManager.java

private CloseableHttpClient createClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    // Provide username and password if specified
    if (username != null) {
        final BasicCredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(new HttpHost(repositoryURL.getHost())),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credProvider);
    }//from   w w  w  .j  a v a 2  s  .c  o m

    // Follow redirects
    builder.setRedirectStrategy(new LaxRedirectStrategy());

    return builder.build();
}

From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Default constructor.//from   w  w  w.  j a  v a  2s .  c  o  m
 *
 * @param host       Hostname of the Neo4j instance.
 * @param port       HTTP port of the Neo4j instance.
 * @param secure    If the connection used SSL.
 * @param properties Properties of the url connection.
 */
public CypherExecutor(String host, Integer port, Boolean secure, Properties properties) throws SQLException {
    this.secure = secure;

    // Create the http client builder
    HttpClientBuilder builder = HttpClients.custom();

    // Adding authentication to the http client if needed
    CredentialsProvider credentialsProvider = getCredentialsProvider(host, port, properties);
    if (credentialsProvider != null)
        builder.setDefaultCredentialsProvider(credentialsProvider);

    // Setting user-agent
    String userAgent = properties.getProperty("useragent");
    builder.setUserAgent("Neo4j JDBC Driver" + (userAgent != null ? " via " + userAgent : ""));
    // Create the http client
    this.http = builder.build();

    // Create the url endpoint
    this.transactionUrl = createTransactionUrl(host, port, secure);

    // Setting autocommit
    this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true")));
}

From source file:org.nuxeo.connect.connector.http.ConnectHttpConnector.java

@Override
protected ConnectServerResponse execServerCall(String url, Map<String, String> headers)
        throws ConnectServerError {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    ProxyHelper.configureProxyIfNeeded(httpClientBuilder, url);
    httpClientBuilder.setConnectionTimeToLive(connectHttpTimeout, TimeUnit.MILLISECONDS);
    HttpGet method = new HttpGet(url);

    for (String name : headers.keySet()) {
        method.addHeader(name, headers.get(name));
    }/*w  w w . j  a v  a2 s. c om*/

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
        // We do not use autoclose on the httpClient nor on the httpResponse since we may return them yet
        // not consumed in the ConnectHttpResponse
        httpClient = httpClientBuilder.build();
        httpResponse = httpClient.execute(method);
        int rc = httpResponse.getStatusLine().getStatusCode();
        switch (rc) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_NO_CONTENT:
        case HttpStatus.SC_NOT_FOUND:
            return new ConnectHttpResponse(httpClient, httpResponse);
        case HttpStatus.SC_UNAUTHORIZED:
            httpResponse.close();
            httpClient.close();
            throw new ConnectSecurityError("Connect server refused authentication (returned 401)");
        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            httpResponse.close();
            httpClient.close();
            throw new ConnectSecurityError("Proxy server require authentication (returned 407)");
        case HttpStatus.SC_GATEWAY_TIMEOUT:
        case HttpStatus.SC_REQUEST_TIMEOUT:
            httpResponse.close();
            httpClient.close();
            throw new ConnectServerError("Timeout " + rc);
        default:
            try {
                String body = EntityUtils.toString(httpResponse.getEntity());
                JSONObject obj = new JSONObject(body);
                String message = obj.getString("message");
                String errorClass = obj.getString("errorClass");
                ConnectServerError error;
                if (ConnectSecurityError.class.getSimpleName().equals(errorClass)) {
                    error = new ConnectSecurityError(message);
                } else if (ConnectClientVersionMismatchError.class.getSimpleName().equals(errorClass)) {
                    error = new ConnectClientVersionMismatchError(message);
                } else {
                    error = new ConnectServerError(message);
                }
                throw error;
            } catch (JSONException e) {
                log.debug("Can't parse server error " + rc, e);
                throw new ConnectServerError("Server returned a code " + rc);
            } finally {
                httpResponse.close();
                httpClient.close();
            }
        }
    } catch (ConnectServerError cse) {
        throw cse;
    } catch (IOException e) {
        IOUtils.closeQuietly(httpResponse);
        IOUtils.closeQuietly(httpClient);
        throw new ConnectServerError("Error during communication with the Nuxeo Connect Server", e);
    }
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

RestClient(CrowdPluginConfiguration config) throws URISyntaxException {
    crowdServer = new URI(config.getCrowdServerUrl()).resolve("rest/usermanagement/1/");

    crowdCreds = new UsernamePasswordCredentials(config.getApplicationName(), config.getApplicationPassword());

    // configure the http client
    RequestConfig.Builder reqConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true)
            .setConnectTimeout(config.getHttpTimeout()).setSocketTimeout(config.getHttpTimeout());

    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.getHttpMaxConnections());
    cm.setDefaultMaxPerRoute(config.getHttpMaxConnections());

    // proxy settings
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (StringUtils.isNotBlank(config.getHttpProxyHost()) && config.getHttpProxyPort() > 0) {
        HttpHost proxy = new HttpHost(config.getHttpProxyHost(), config.getHttpProxyPort());
        reqConfigBuilder.setProxy(proxy);

        if (config.getHttpProxyUsername() != null && config.getHttpProxyPassword() != null) {
            credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                    config.getHttpProxyUsername(), config.getHttpProxyPassword()));
        }//from  www . j  av a2  s.c  om
    }

    RequestConfig reqConfig = reqConfigBuilder.build();
    HttpClientBuilder hcBuilder = HttpClients.custom().setMaxConnPerRoute(config.getHttpMaxConnections())
            .setMaxConnTotal(config.getHttpMaxConnections()).setConnectionManager(cm)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(reqConfig);

    // handling of compressed responses
    hcBuilder.addInterceptorLast(new CompressedHttpResponseInterceptor());

    client = hcBuilder.build();

    if (LOG.isDebugEnabled()) {
        LOG.debug("HTTP Client config");
        LOG.debug(config.getCrowdServerUrl());
        LOG.debug("PROPERTY_THREADPOOL_SIZE:" + cm.getMaxTotal());
        LOG.debug("PROPERTY_READ_TIMEOUT:" + reqConfig.getSocketTimeout());
        LOG.debug("PROPERTY_CONNECT_TIMEOUT:" + reqConfig.getConnectTimeout());
        if (reqConfig.getProxy() != null) {
            LOG.debug("PROPERTY_PROXY_URI:" + reqConfig.getProxy().toString());
        }
        LOG.debug("Crowd application name:" + config.getApplicationName());
    }
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain apiKey for player id./* w  w  w  . j  a va2s  . c  o m*/
 *
 * @param playerId
 *            The player id
 * @return The apiKey for the player
 */
public String getApiKey(String playerId) throws IOException {
    String jwt = getClientJwtForId(playerId);

    HttpClient client = null;
    if ("development".equals(System.getenv("CONCIERGE_PLAYER_MODE"))) {
        System.out.println("Using development mode player connection. (DefaultSSL,NoHostNameValidation)");
        try {
            HttpClientBuilder b = HttpClientBuilder.create();

            //use the default ssl context, we have a trust store configured for player cert.
            SSLContext sslContext = SSLContext.getDefault();

            //use a very trusting truststore.. (not needed..)
            //SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

            b.setSSLContext(sslContext);

            //disable hostname validation, because we'll need to access the cert via a different hostname.
            b.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            client = b.build();
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else {
        client = HttpClientBuilder.create().build();
    }
    HttpGet hg = new HttpGet(playerLocation + "/" + playerId + "?jwt=" + jwt);

    System.out.println("Building web target " + hg.getURI().toString());

    try {
        // Make GET request using the specified target, get result as a
        // string containing JSON
        HttpResponse r = client.execute(hg);
        String result = new BasicResponseHandler().handleResponse(r);

        // Parse the JSON response, and retrieve the apiKey field value.
        ObjectMapper om = new ObjectMapper();
        JsonNode jn = om.readValue(result, JsonNode.class);

        return jn.get("apiKey").textValue();
    } catch (HttpResponseException hre) {
        System.out.println(
                "Error communicating with player service: " + hre.getStatusCode() + " " + hre.getMessage());
        throw hre;
    } catch (ResponseProcessingException rpe) {
        System.out.println("Error processing response " + rpe.getResponse().toString());
        throw new IOException(rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        //bad stuff.
        System.out.println("Hmm.. " + ex.getMessage());
        throw new IOException(ex);
    } catch (IOException io) {
        System.out.println("Utoh.. " + io.getMessage());
        throw new IOException(io);
    }

}

From source file:com.activiti.service.activiti.ActivitiClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

    SSLConnectionSocketFactory sslsf = null;
    try {/* w  w w . jav  a  2 s .  c  om*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        log.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    if (sslsf != null) {
        httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    return httpClientBuilder.build();
}