Example usage for org.apache.http.nio.client.methods AsyncCharConsumer AsyncCharConsumer

List of usage examples for org.apache.http.nio.client.methods AsyncCharConsumer AsyncCharConsumer

Introduction

In this page you can find the example usage for org.apache.http.nio.client.methods AsyncCharConsumer AsyncCharConsumer.

Prototype

public AsyncCharConsumer() 

Source Link

Usage

From source file:httpasync.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from w  ww  .ja  v  a  2 s  .  co  m
        // Start the client
        httpclient.start();

        // Execute request
        final HttpGet request1 = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request1, null);
        // and wait until response is received
        HttpResponse response1 = future.get();
        System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine());

        // One most likely would want to use a callback for operation result
        final CountDownLatch latch1 = new CountDownLatch(1);
        final HttpGet request2 = new HttpGet("http://www.apache.org/");
        httpclient.execute(request2, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response2) {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine());
            }

            @Override
            public void failed(final Exception ex) {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch1.countDown();
                System.out.println(request2.getRequestLine() + " cancelled");
            }

        });
        latch1.await();

        // In real world one most likely would want also want to stream
        // request and response body content
        final CountDownLatch latch2 = new CountDownLatch(1);
        final HttpGet request3 = new HttpGet("http://www.apache.org/");
        HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3);
        AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() {

            HttpResponse response;

            @Override
            protected void onResponseReceived(final HttpResponse response) {
                this.response = response;
            }

            @Override
            protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
                // Do something useful
            }

            @Override
            protected void releaseResources() {
            }

            @Override
            protected HttpResponse buildResult(final HttpContext context) {
                return this.response;
            }

        };
        httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response3) {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine());
            }

            @Override
            public void failed(final Exception ex) {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch2.countDown();
                System.out.println(request2.getRequestLine() + " cancelled");
            }

        });
        latch2.await();

    } finally {
        httpclient.close();
    }
}

From source file:io.galeb.services.healthchecker.testers.ApacheHttpClientTester.java

public boolean connect() throws RuntimeException, InterruptedException, ExecutionException {
    if (url == null || returnType == null || expectedReturn == null) {
        return false;
    }/*from w w  w  . j ava  2  s.co  m*/
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        final CountDownLatch latch = new CountDownLatch(1);
        final HttpGet request = new HttpGet(url);
        request.setHeader(HttpHeaders.HOST, host);
        final HttpAsyncRequestProducer producer = HttpAsyncMethods.create(request);
        final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
                .setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout)
                .setConnectionRequestTimeout(defaultTimeout).build();
        request.setConfig(requestConfig);
        final AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>() {

            HttpResponse response;

            @Override
            protected void onCharReceived(CharBuffer buf, IOControl iocontrol) throws IOException {
                return;
            }

            @Override
            protected HttpResponse buildResult(HttpContext context) throws Exception {
                return response;
            }

            @Override
            protected void onResponseReceived(HttpResponse response) throws HttpException, IOException {
                this.response = response;
            }

        };
        httpclient.execute(producer, consumer, new FutureCallback<HttpResponse>() {

            @Override
            public void cancelled() {
                latch.countDown();
                isOk = false;
            }

            @Override
            public void completed(HttpResponse response) {
                latch.countDown();

                final int statusCode = response.getStatusLine().getStatusCode();
                InputStream contentIS = null;
                String content = "";
                try {
                    contentIS = response.getEntity().getContent();
                    content = IOUtils.toString(contentIS);

                } catch (IllegalStateException | IOException e) {
                    logger.ifPresent(log -> log.debug(e));
                }

                if (returnType.startsWith("httpCode")) {
                    returnType = returnType.replaceFirst("httpCode", "");
                }
                // isOk = statusCode == Integer.parseInt(returnType); // Disable temporarily statusCode check
                isOk = true;
            }

            @Override
            public void failed(Exception e) {
                latch.countDown();
                isOk = false;
                logger.ifPresent(log -> log.debug(e));
            }

        });
        latch.await();

    } catch (final RuntimeException e) {
        isOk = false;
        logger.ifPresent(log -> log.error(e));
    } finally {
        try {
            httpclient.close();
        } catch (final IOException e) {
            logger.ifPresent(log -> log.debug(e));
        }
    }
    return isOk;
}