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:rc.championship.platform.decoder.lap.publisher.RccLapPublisher.java

private void send(List<Lap> laps) {

    try {/*  www . j  a  va2s  .  c  o m*/
        String json = convertToJsonArray(laps);

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://localhost:8080/api/laps");
        StringEntity input = new StringEntity(json);
        post.setEntity(input);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.jboss.aerogear.unifiedpush.admin.ui.utils.UpsOpenshiftStatusCheck.java

@Override
public boolean execute() throws StatusCheckException {
    HttpClient client = HttpClientBuilder.create().build();

    int statusCode;
    try {/*w w  w .j a  v  a  2 s.  c om*/
        statusCode = client.execute(new HttpGet(uri)).getStatusLine().getStatusCode();
    } catch (IOException e) {
        throw new StatusCheckException("Error when checking status code of " + uri.toString(), e);
    }

    logger.fine(String.format("Status code: %s", statusCode));
    return statusCode == HttpStatus.SC_OK;
}

From source file:org.apache.gobblin.writer.AvroHttpWriterBuilder.java

@Override
public AvroHttpWriterBuilder fromConfig(Config config) {
    config = config.withFallback(FALLBACK);
    ApacheHttpClient client = new ApacheHttpClient(HttpClientBuilder.create(), config, broker);
    this.client = client;

    String urlTemplate = config.getString(HttpConstants.URL_TEMPLATE);
    String verb = config.getString(HttpConstants.VERB);
    String contentType = config.getString(HttpConstants.CONTENT_TYPE);
    this.asyncRequestBuilder = new ApacheHttpRequestBuilder(urlTemplate, verb, contentType);

    Set<String> errorCodeWhitelist = HttpUtils.getErrorCodeWhitelist(config);
    this.responseHandler = new ApacheHttpResponseHandler(errorCodeWhitelist);
    return this;
}

From source file:de.bytefish.fcmjava.client.http.apache.DefaultHttpClient.java

public DefaultHttpClient(IFcmClientSettings settings) {
    this(settings, HttpClientBuilder.create());
}

From source file:juzu.impl.bridge.request.AbstractRequestEntityReader.java

@Test
public void testPost() throws Exception {
    driver.get(applicationURL().toString());
    WebElement elt = driver.findElement(By.id("post"));
    String url = elt.getText();/*from www. ja  v a2s  . c o m*/
    data = null;
    HttpPost post = new HttpPost(url);
    post.setEntity(new ByteArrayEntity("<foo></foo>".getBytes(Tools.ISO_8859_1),
            ContentType.create("text/foo", Tools.ISO_8859_1)));
    HttpClient client = HttpClientBuilder.create().build();
    client.execute(post);
    assertNotNull(data);
    assertEquals("<foo></foo>", new String(data, Tools.ISO_8859_1));
}

From source file:org.sisto.jeeplate.webserver.jetty.EmbeddedWebserverTest.java

@Test
public void testWebserver() throws Exception {
    HttpClient browser = HttpClientBuilder.create().build();
    HttpGet getRequest = new HttpGet(String.format("http://localhost:%s/%s", SERVER_PORT, SERVER_PATH));
    HttpResponse response = browser.execute(getRequest);
    int responseStatusCode = response.getStatusLine().getStatusCode();

    if (responseStatusCode != 200) {
        Assert.fail(String.format("Jetty returned '%s'!", responseStatusCode));
    }//  w w w .j  a  v  a2  s  . co  m
}

From source file:org.apache.hadoop.gateway.services.metrics.impl.instr.InstrHttpClientBuilderProvider.java

@Override
public HttpClientBuilder getInstrumented(MetricsContext metricsContext) {
    MetricRegistry registry = (MetricRegistry) metricsContext
            .getProperty(DefaultMetricsService.METRICS_REGISTRY);
    return HttpClientBuilder.create()
            .setRequestExecutor(new InstrumentedHttpRequestExecutor(registry, TOPOLOGY_URL_AND_METHOD))
            .setConnectionManager(new PoolingHttpClientConnectionManager());
}

From source file:communication.Communicator.java

/**
 * Gets all the cartrackers from the Movementsystem api
 *
 * @return A list with all the cartrackers from the Movementsystem api
 * @throws IOException Could be thrown when executing the http request, or
 * when converting the result to a String
 *//*  w ww.j  a va2 s . c o m*/
public static List<CarTracker> getAllCartrackers() throws IOException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(BASE_URL_PRODUCTION);
    HttpResponse response = httpClient.execute(get);

    String responseString = EntityUtils.toString(response.getEntity(), CHARACTER_SET);
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    try {
        return gson.fromJson(responseString, new TypeToken<List<CarTracker>>() {
        }.getType());
    } catch (JsonSyntaxException ex) {
        Logger.getLogger(Communicator.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException(ex.getMessage());
    }
}

From source file:org.fcrepo.apix.registry.impl.HttpClientFactory.java

/**
 * Construct a new HttpClient./*from   w  w  w.  j av  a 2 s.c  o  m*/
 *
 * @return HttpClient impl.
 */
public CloseableHttpClient getClient() {
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    return HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}

From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java

/**
 * Executes the REST request described by the {@link RestEvent}
 * //from   w  w w  .j a v a  2s .  co  m
 * @param restEvent The {@link RestEvent} to process
 * @return A result of the execution
 * @throws RestEventApiRuntimeException In case of non managed errors
 */
public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException {
    RestClientExecutionResult result = new RestClientExecutionResult();
    String url = restEvent.getUrl();
    CloseableHttpClient client = null;
    HttpUriRequest request = null;
    Integer responseCode = null;

    try {
        //Request custom configs
        RequestConfig.Builder requestBuilder = RequestConfig.custom();
        requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout());
        requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout());

        client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build();

        //Determine the method to execute
        switch (restEvent.getMethod()) {
        case GET:
            request = new HttpGet(url);
            break;
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        case DELETE:
            request = new HttpDelete(url);
            break;
        case PATCH:
            request = new HttpPatch(url);
            break;
        case HEAD:
            request = new HttpHead(url);
            break;
        default:
            throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method");
        }

        //Set the body for eligible methods
        if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody()));
        }

        //Set headers
        if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) {
            for (String strHeader : restEvent.getHeaders()) {
                CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1);
                headerBuffer.append(strHeader);
                request.addHeader(new BufferedHeader(headerBuffer));
            }
        }

        HttpResponse response = client.execute(request);
        responseCode = response.getStatusLine().getStatusCode();

        result.setState(RestClientCallState.OK);
    } catch (ConnectTimeoutException e) {
        result.setState(RestClientCallState.TIMEOUT);
    } catch (Exception e) {
        throw new RestEventApiRuntimeException("Un error occured while processing rest event", e);
    } finally {
        result.setResponseCode(responseCode);

        try {
            client.close();
        } catch (Exception e2) {
            logger.warn("Unable to close HTTP client", e2);
        }
    }

    return result;
}