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

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

Introduction

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

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:org.outermedia.solrfusion.adapter.solr.DefaultSolrAdapterTest.java

@Test
@Ignore//from ww w . j av a2s  . co m
public void testHttpClientGet() throws IOException, URISyntaxException {
    HttpClient client = HttpClientBuilder.create().build();
    URI uri = new URI("http", null, "www.outermedia.de", 80, "/", "q=bla", null);
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);

    Header[] header = response.getHeaders("Server");
    Assert.assertTrue("Server is Ubuntu", header[0].getValue().contains("Ubuntu"));

    // Get the response
    HttpEntity entity = response.getEntity();
    Assert.assertEquals("Content-type is utf8 hmtl", "text/html; charset=utf-8",
            entity.getContentType().getValue());

    String content = new Scanner(response.getEntity().getContent(), "UTF-8").useDelimiter("\\A").next();
    System.out.println(content);

}

From source file:com.jive.myco.seyren.core.service.notification.HttpNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;//from   w ww.j  a va2 s.  co m
    }
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("preview", getPreviewImage(check));

    HttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost(subscription.getTarget());
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.wildfly.test.integration.microprofile.config.smallrye.converter.MicroProfileConfigConvertersTestCase.java

@Test
public void testConverterPriority() throws Exception {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpResponse response = client.execute(new HttpGet(url + "custom-converter/test"));
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        String text = getContent(response);
        AssertUtils.assertTextContainsProperty(text, "int_converted_to_102_by_priority_of_custom_converter",
                "102");
        // TODO - enable this when https://issues.jboss.org/browse/WFWIP-60 is resolved
        //AssertUtils.assertTextContainsProperty(text, "string_converted_by_priority_of_custom_converter", "Property converted by HighPriorityStringConverter1");
    }/*  w w  w  .j ava2s .  co m*/
}

From source file:org.wise.vle.domain.webservice.http.impl.HttpRestTransportImpl.java

/**
 * Constructs a newly allocated HttpRestTransportImpl object.
 *//*from  w ww . ja  v  a2  s  .  co m*/
public HttpRestTransportImpl() {
    // Must manually release the connection by calling releaseConnection()
    // on the method, otherwise there will be a resource leak. Refer to
    // http://jakarta.apache.org/commons/httpclient/threading.html
    this.client = HttpClientBuilder.create().build();
    this.logger = LogFactory.getLog(this.getClass());
}

From source file:com.exquance.jenkins.plugins.conduit.ConduitAPIClient.java

/**
 * Call the conduit API of Phabricator/*from w w w. jav  a 2  s . c  om*/
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(responseBody.toString(), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}

From source file:com.comcast.viper.hlsparserj.PlaylistFactory.java

/**
 * Factory method to generate playlist object. This method uses a very
 * simple HTTP client to download the URL passed by the playlistURL
 * parameters. This method should not be used for applications that require
 * high-performance, as the HTTP connection management is very basic. If
 * your application has high performance requirements us the parsePlaylist
 * method that takes an InputStream./*from   www  .  j  a va2  s.  c o  m*/
 *
 * @param playlistVersion version of the playlist (V12 is the default)
 * @param playlistURL URL pointing to a playlist
 * @return parsed playlist
 * @throws IOException on connection and parsing exceptions
 */
public static AbstractPlaylist parsePlaylist(final PlaylistVersion playlistVersion, final URL playlistURL)
        throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient httpClient = builder.build();
    PlaylistParser parser = new PlaylistParser();

    try {
        InputStream playlistStream = getPlaylistInputStream(httpClient, playlistURL);
        parser.parse(playlistStream);
    } finally {
        httpClient.close();
    }

    return getVersionSpecificPlaylist(parser, playlistVersion);
}

From source file:com.everis.storage.service.StorageService.java

private void restClient(Transaction transaction) {
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {//from   w  w w  . j  ava  2  s  . c o m
        InstanceInfo service = discoverService();
        System.out.println("DISCOVERY: " + service);
        // specify the host, protocol, and port            
        HttpHost target = new HttpHost(service.getHostName(), service.getPort(), "http");

        // specify the get request
        HttpPost postRequest = new HttpPost("/transactions");

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
        StringEntity jsonEntity = new StringEntity(gson.toJson(transaction));

        postRequest.setEntity(jsonEntity);
        postRequest.addHeader(new BasicHeader("Content-type", "application/json"));

        System.out.println("executing request to " + target);

        HttpResponse httpResponse = httpClient.execute(target, postRequest);
        HttpEntity entity = httpResponse.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.sonatype.spice.zapper.client.hc4.Hc4ClientBuilder.java

public Hc4Client build() {
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", SSLConnectionSocketFactory.getSystemSocketFactory()).build();

    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(200);//from  w ww  . j  a  v  a 2s. c  o m
    cm.setDefaultMaxPerRoute(parameters.getMaximumTrackCount());

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(cm)
            .setUserAgent("Zapper/1.0-HC4");

    if (proxyServer != null) {
        httpClientBuilder.setProxy(proxyServer);
    }
    if (credentialsProvider != null) {
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    return new Hc4Client(parameters, remoteUrl, httpClientBuilder.build(),
            preemptiveAuth ? credentialsProvider : null);
}

From source file:org.wildfly.test.integration.microprofile.config.smallrye.management.config_source_provider.ConfigSourceProviderFromClassTestCase.java

@Test
public void testGetWithConfigProperties() throws Exception {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpResponse response = client.execute(new HttpGet(url + "custom-config-source-provider/test"));
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        String text = getContent(response);
        AssertUtils.assertTextContainsProperty(text, CustomConfigSource.PROP_NAME,
                CustomConfigSource.PROP_VALUE);
    }/*from  www  .j  a v a2  s .  c o  m*/
}