Search in sources :

Example 91 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class Http1IntegrationTest method testHeadPipelined.

@Test
public void testHeadPipelined() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Queue<Future<Message<HttpResponse, String>>> queue = new LinkedList<>();
    for (int i = 0; i < 5; i++) {
        queue.add(streamEndpoint.execute(new BasicRequestProducer(Method.HEAD, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
    }
    while (!queue.isEmpty()) {
        final Future<Message<HttpResponse, String>> future = queue.remove();
        final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        Assertions.assertNotNull(result);
        final HttpResponse response1 = result.getHead();
        Assertions.assertNotNull(response1);
        Assertions.assertEquals(200, response1.getCode());
        Assertions.assertNull(result.getBody());
    }
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) LinkedList(java.util.LinkedList) Future(java.util.concurrent.Future) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Test(org.junit.Test)

Example 92 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class AsyncServerBootstrapFilterTest method testFilters.

@Test
public void testFilters() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTP);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost("http", "localhost", address.getPort());
    final Future<Message<HttpResponse, String>> resultFuture = requester.execute(new BasicRequestProducer(Method.POST, target, "/filters", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message = resultFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    assertThat(message, CoreMatchers.notNullValue());
    final HttpResponse response = message.getHead();
    assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final Header testFilterHeader = response.getHeader("X-Test-Filter");
    assertThat(testFilterHeader, CoreMatchers.notNullValue());
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.jupiter.api.Test)

Example 93 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class AsyncPipelinedRequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
    // Create and start requester
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final HttpHost target = new HttpHost("httpbin.org");
    final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
    final AsyncClientEndpoint clientEndpoint = future.get();
    final CountDownLatch latch = new CountDownLatch(requestUris.length);
    for (final String requestUri : requestUris) {
        clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

            @Override
            public void completed(final Message<HttpResponse, String> message) {
                latch.countDown();
                final HttpResponse response = message.getHead();
                final String body = message.getBody();
                System.out.println(requestUri + "->" + response.getCode());
                System.out.println(body);
            }

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

            @Override
            public void cancelled() {
                latch.countDown();
                System.out.println(requestUri + " cancelled");
            }
        });
    }
    latch.await();
    // Manually release client endpoint when done !!!
    clientEndpoint.releaseAndDiscard();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 94 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class AsyncRequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
    // Create and start requester
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final HttpHost target = new HttpHost("httpbin.org");
    final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    final CountDownLatch latch = new CountDownLatch(requestUris.length);
    for (final String requestUri : requestUris) {
        requester.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), Timeout.ofSeconds(5), new FutureCallback<Message<HttpResponse, String>>() {

            @Override
            public void completed(final Message<HttpResponse, String> message) {
                final HttpResponse response = message.getHead();
                final String body = message.getBody();
                System.out.println(requestUri + "->" + response.getCode());
                System.out.println(body);
                latch.countDown();
            }

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

            @Override
            public void cancelled() {
                System.out.println(requestUri + " cancelled");
                latch.countDown();
            }
        });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 95 with BasicResponseConsumer

use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.

the class H2ConscriptRequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    // Create and start requester
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
    final SSLContext sslContext = SSLContexts.custom().setProvider(Conscrypt.newProvider()).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setTlsStrategy(new ConscryptClientTlsStrategy(sslContext)).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final HttpHost target = new HttpHost("https", "nghttp2.org", 443);
    final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
    final CountDownLatch latch = new CountDownLatch(requestUris.length);
    for (final String requestUri : requestUris) {
        final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofDays(5));
        final AsyncClientEndpoint clientEndpoint = future.get();
        clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

            @Override
            public void completed(final Message<HttpResponse, String> message) {
                clientEndpoint.releaseAndReuse();
                final HttpResponse response = message.getHead();
                final String body = message.getBody();
                System.out.println(requestUri + "->" + response.getCode() + " " + response.getVersion());
                System.out.println(body);
                latch.countDown();
            }

            @Override
            public void failed(final Exception ex) {
                clientEndpoint.releaseAndDiscard();
                System.out.println(requestUri + "->" + ex);
                latch.countDown();
            }

            @Override
            public void cancelled() {
                clientEndpoint.releaseAndDiscard();
                System.out.println(requestUri + " cancelled");
                latch.countDown();
            }
        });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) HttpHost(org.apache.hc.core5.http.HttpHost) List(java.util.List) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) HttpResponse(org.apache.hc.core5.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) ConscryptClientTlsStrategy(org.apache.hc.core5.http2.ssl.ConscryptClientTlsStrategy) Header(org.apache.hc.core5.http.Header) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2Config(org.apache.hc.core5.http2.config.H2Config)

Aggregations

StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)94 Message (org.apache.hc.core5.http.Message)93 HttpResponse (org.apache.hc.core5.http.HttpResponse)92 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)86 InetSocketAddress (java.net.InetSocketAddress)84 Test (org.junit.Test)73 HttpRequest (org.apache.hc.core5.http.HttpRequest)41 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)40 HttpHost (org.apache.hc.core5.http.HttpHost)38 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)36 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)30 IOException (java.io.IOException)27 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)26 HttpException (org.apache.hc.core5.http.HttpException)25 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)23 InterruptedIOException (java.io.InterruptedIOException)22 Header (org.apache.hc.core5.http.Header)20 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)20 Future (java.util.concurrent.Future)18 ExecutionException (java.util.concurrent.ExecutionException)17