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:de.bytefish.fcmjava.client.utils.HttpUtils.java

private static <TRequestMessage> void internalPost(HttpClientBuilder httpClientBuilder,
        IFcmClientSettings settings, TRequestMessage requestMessage) throws Exception {

    try (CloseableHttpClient client = httpClientBuilder.build()) {

        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(JsonUtils.getAsJsonString(requestMessage)));

        // Execute the Request:
        try (CloseableHttpResponse response = client.execute(httpPost)) {

            // Get the HttpEntity:
            HttpEntity entity = response.getEntity();

            // Let's be a good citizen and consume the HttpEntity:
            if (entity != null) {

                // Make Sure it is fully consumed:
                EntityUtils.consume(entity);
            }//from www.  ja v  a  2  s . co m
        }
    }
}

From source file:ninja.siden.internal.Testing.java

static CloseableHttpClient client() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(200).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return builder.build();
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String getFileInfo(String baseUrl, String externalId, String receiverAddress,
        String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;//from w  w  w.  j  a  v  a2s .  c  o m
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {
        HttpGet httpget = new HttpGet(baseUrl + "submissions/" + receiverAddress + "/" + externalId);

        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httpget, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httpget.addHeader("Accept", "application/json");
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR getting File Info : ", e);
    }
    return ret;
}

From source file:de.bytefish.fcmjava.client.utils.HttpUtils.java

private static <TRequestMessage, TResponseMessage> TResponseMessage internalPost(
        HttpClientBuilder httpClientBuilder, IFcmClientSettings settings, TRequestMessage requestMessage,
        Class<TResponseMessage> responseType) throws Exception {

    try (CloseableHttpClient client = httpClientBuilder.build()) {

        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Get the JSON representation of the given request message:
        String requestJson = JsonUtils.getAsJsonString(requestMessage);

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(requestJson));

        // Execute the Request:
        try (CloseableHttpResponse response = client.execute(httpPost)) {

            // Get the HttpEntity of the Response:
            HttpEntity entity = response.getEntity();

            // If we don't have a HttpEntity, we won't be able to convert it:
            if (entity == null) {
                // Simply return null (no response) in this case:
                return null;
            }//  ww w  .  ja va 2  s  . c  o m

            // Get the JSON Body:
            String responseBody = EntityUtils.toString(entity);

            // Make Sure it is fully consumed:
            EntityUtils.consume(entity);

            // And finally return the Response Message:
            return JsonUtils.getEntityFromString(responseBody, responseType);
        }
    }
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;/*from   w  w w . j a  v  a 2s. c  o m*/

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactoryIntegrationTest.java

private static void createClient() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();

    socketFactoryRegistry.register("http", PlainConnectionSocketFactory.INSTANCE);

    socketFactoryRegistry.register("https", createSSLSocketFactory());

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry.build());
    connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from w w w .j a  v  a  2s . c om
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(timeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(connMgr);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:org.springframework.social.openidconnect.api.impl.GAECompatibleClientHttpRequestFactorySelector.java

public static ClientHttpRequestFactory getRequestFactory() {
    Properties properties = System.getProperties();
    String proxyHost = properties.getProperty("http.proxyHost");
    int proxyPort = properties.containsKey("http.proxyPort")
            ? Integer.valueOf(properties.getProperty("http.proxyPort"))
            : 80;//www.j  a  va  2 s.c  o m
    if (HTTP_COMPONENTS_AVAILABLE) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        if (proxyHost != null) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClientBuilder.setProxy(proxy);
        }
        return HttpComponentsClientRequestFactoryCreator.createRequestFactory(httpClientBuilder.build(),
                proxyHost, proxyPort);
    } else {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        if (proxyHost != null) {
            requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        }
        return requestFactory;
    }
}

From source file:eu.delving.sip.base.HttpClientFactory.java

public static HttpClient createHttpClient(File storageDirectory) {
    HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries();
    builder.setConnectionManager(new PoolingHttpClientConnectionManager());
    if (!StorageFinder.isStandalone(storageDirectory)) {
        String serverUrl = String.format("http://%s", getHostPort(storageDirectory));
        handleProxy(serverUrl, builder);
    }/* w  w w  . ja v a  2s .c  om*/
    return builder.build();
}

From source file:org.bedework.util.http.HttpUtil.java

public static CloseableHttpClient getClient(final boolean disableRedirects) {
    final HttpClientBuilder bldr = HttpClientBuilder.create();

    if (disableRedirects) {
        bldr.disableRedirectHandling();/*from w w  w .  j  a v a2 s  .  c  om*/
    }

    return bldr.build();
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.v1.utils.HttpSolrClientUtils.java

/**
 * Creates the {@link HttpClient} to use with the Solrj
 *
 * @param url the Solr server url//  www . j  av  a  2s. c o m
 * @param username the {@link RetrieveAndRank} service username
 * @param password the {@link RetrieveAndRank} service password
 * @return the {@link HttpClient}
 */
public static HttpClient createHttpClient(String url, String username, String password) {
    URI scopeUri = URI.create(url);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build())
            .setDefaultCredentialsProvider(credentialsProvider)
            .addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder.build();
}