Search in sources :

Example 1 with BasicResponseConsumer

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

the class H2RequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    // Create and start requester
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).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("nghttp2.org");
    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.ofSeconds(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());
                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 : 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) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) List(java.util.List) H2Config(org.apache.hc.core5.http2.config.H2Config) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 2 with BasicResponseConsumer

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

the class H2ViaHttp1ProxyExecutionExample method main.

public static void main(final String[] args) throws Exception {
    // Create and start requester
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.NEGOTIATE).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)");
            }
        }
    }).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 proxy = new HttpHost("localhost", 8888);
    final HttpHost target = new HttpHost("https", "nghttp2.org");
    final ComplexFuture<AsyncClientEndpoint> tunnelFuture = new ComplexFuture<>(null);
    tunnelFuture.setDependency(requester.connect(proxy, Timeout.ofSeconds(30), null, new FutureContribution<AsyncClientEndpoint>(tunnelFuture) {

        @Override
        public void completed(final AsyncClientEndpoint endpoint) {
            if (endpoint instanceof TlsUpgradeCapable) {
                final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, proxy, target.toHostString());
                endpoint.execute(new BasicRequestProducer(connect, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), new FutureContribution<Message<HttpResponse, Void>>(tunnelFuture) {

                    @Override
                    public void completed(final Message<HttpResponse, Void> message) {
                        final HttpResponse response = message.getHead();
                        if (response.getCode() == HttpStatus.SC_OK) {
                            ((TlsUpgradeCapable) endpoint).tlsUpgrade(target, new FutureContribution<ProtocolIOSession>(tunnelFuture) {

                                @Override
                                public void completed(final ProtocolIOSession protocolSession) {
                                    System.out.println("Tunnel to " + target + " via " + proxy + " established");
                                    tunnelFuture.completed(endpoint);
                                }
                            });
                        } else {
                            tunnelFuture.failed(new HttpException("Tunnel refused: " + new StatusLine(response)));
                        }
                    }
                });
            } else {
                tunnelFuture.failed(new IllegalStateException("TLS upgrade not supported"));
            }
        }
    }));
    final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
    final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
    try {
        final CountDownLatch latch = new CountDownLatch(requestUris.length);
        for (final String requestUri : requestUris) {
            endpoint.execute(new BasicRequestProducer(Method.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), 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();
    } finally {
        endpoint.releaseAndDiscard();
    }
    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) ProtocolIOSession(org.apache.hc.core5.reactor.ProtocolIOSession) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) TlsUpgradeCapable(org.apache.hc.core5.http.nio.ssl.TlsUpgradeCapable) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) HttpHost(org.apache.hc.core5.http.HttpHost) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpException(org.apache.hc.core5.http.HttpException) StatusLine(org.apache.hc.core5.http.message.StatusLine) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) RequestLine(org.apache.hc.core5.http.message.RequestLine) Header(org.apache.hc.core5.http.Header) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) FutureContribution(org.apache.hc.core5.concurrent.FutureContribution) H2Config(org.apache.hc.core5.http2.config.H2Config) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture)

Example 3 with BasicResponseConsumer

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

the class H2AlpnTest method testALPN.

@Test
public void testALPN() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
    final Future<Message<HttpResponse, String>> resultFuture1 = requester.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), TIMEOUT, null);
    final Message<HttpResponse, String> message1;
    try {
        message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    } catch (final ExecutionException e) {
        final Throwable cause = e.getCause();
        assertFalse(h2Allowed, "h2 negotiation was enabled, but h2 was not negotiated");
        assertTrue(cause instanceof ProtocolNegotiationException);
        assertEquals("ALPN: missing application protocol", cause.getMessage());
        assertTrue(strictALPN, "strict ALPN mode was not enabled, but the client negotiator still threw");
        return;
    }
    assertTrue(h2Allowed, "h2 negotiation was disabled, but h2 was negotiated");
    assertThat(message1, CoreMatchers.notNullValue());
    final HttpResponse response1 = message1.getHead();
    assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
    final String body1 = message1.getBody();
    assertThat(body1, CoreMatchers.equalTo("some stuff"));
}
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) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) ProtocolNegotiationException(org.apache.hc.core5.http2.impl.nio.ProtocolNegotiationException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 4 with BasicResponseConsumer

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

the class H2IntegrationTest method testLargePost.

@Test
public void testLargePost() throws Exception {
    server.register("*", () -> new EchoHandler(2048));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.POST, createRequestURI(serverEndpoint, "/echo"), new MultiLineEntityProducer("0123456789abcdef", 5000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    final String s1 = result1.getBody();
    Assertions.assertNotNull(s1);
    final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("0123456789abcdef", t1.nextToken());
    }
}
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) StringTokenizer(java.util.StringTokenizer) Test(org.junit.Test)

Example 5 with BasicResponseConsumer

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

the class H2IntegrationTest method testPrematureResponse.

@Test
public void testPrematureResponse() throws Exception {
    server.register("*", new Supplier<AsyncServerExchangeHandler>() {

        @Override
        public AsyncServerExchangeHandler get() {
            return new AsyncServerExchangeHandler() {

                private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();

                @Override
                public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
                    capacityChannel.update(Integer.MAX_VALUE);
                }

                @Override
                public void consume(final ByteBuffer src) throws IOException {
                }

                @Override
                public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                }

                @Override
                public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
                    final AsyncResponseProducer producer;
                    final Header h = request.getFirstHeader("password");
                    if (h != null && "secret".equals(h.getValue())) {
                        producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
                    } else {
                        producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
                    }
                    responseProducer.set(producer);
                    producer.sendResponse(responseChannel, context);
                }

                @Override
                public int available() {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    return producer.available();
                }

                @Override
                public void produce(final DataStreamChannel channel) throws IOException {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    producer.produce(channel);
                }

                @Override
                public void failed(final Exception cause) {
                }

                @Override
                public void releaseResources() {
                }
            };
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcdef", 5000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
    Assertions.assertNotNull("You shall not pass", result1.getBody());
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

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