Search in sources :

Example 21 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-client by apache.

the class HttpAsyncClientProtocolNegotiationStarter method createHandler.

@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
    final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory;
    final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
    if (STREAM_LOG.isDebugEnabled() || HEADER_LOG.isDebugEnabled() || FRAME_LOG.isDebugEnabled() || FRAME_PAYLOAD_LOG.isDebugEnabled() || FLOW_CTRL_LOG.isDebugEnabled()) {
        final String id = ioSession.getId();
        http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor, h1Config, charCodingConfig, http1ConnectionReuseStrategy, http1ResponseParserFactory, http1RequestWriterFactory, new Http1StreamListener() {

            @Override
            public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
                if (HEADER_LOG.isDebugEnabled()) {
                    HEADER_LOG.debug("{} >> {}", id, new RequestLine(request));
                    for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
                        HEADER_LOG.debug("{} >> {}", id, it.next());
                    }
                }
            }

            @Override
            public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
                if (HEADER_LOG.isDebugEnabled()) {
                    HEADER_LOG.debug("{} << {}", id, new StatusLine(response));
                    for (final Iterator<Header> it = response.headerIterator(); it.hasNext(); ) {
                        HEADER_LOG.debug("{} << {}", id, it.next());
                    }
                }
            }

            @Override
            public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
                if (STREAM_LOG.isDebugEnabled()) {
                    if (keepAlive) {
                        STREAM_LOG.debug("{} Connection is kept alive", id);
                    } else {
                        STREAM_LOG.debug("{} Connection is not kept alive", id);
                    }
                }
            }
        });
        http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor, exchangeHandlerFactory, h2Config, charCodingConfig, new H2StreamListener() {

            final FramePrinter framePrinter = new FramePrinter();

            private void logFrameInfo(final String prefix, final RawFrame frame) {
                try {
                    final LogAppendable logAppendable = new LogAppendable(FRAME_LOG, prefix);
                    framePrinter.printFrameInfo(frame, logAppendable);
                    logAppendable.flush();
                } catch (final IOException ignore) {
                }
            }

            private void logFramePayload(final String prefix, final RawFrame frame) {
                try {
                    final LogAppendable logAppendable = new LogAppendable(FRAME_PAYLOAD_LOG, prefix);
                    framePrinter.printPayload(frame, logAppendable);
                    logAppendable.flush();
                } catch (final IOException ignore) {
                }
            }

            private void logFlowControl(final String prefix, final int streamId, final int delta, final int actualSize) {
                FLOW_CTRL_LOG.debug("{} stream {} flow control {} -> {}", prefix, streamId, delta, actualSize);
            }

            @Override
            public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
                if (HEADER_LOG.isDebugEnabled()) {
                    for (int i = 0; i < headers.size(); i++) {
                        HEADER_LOG.debug("{} << {}", id, headers.get(i));
                    }
                }
            }

            @Override
            public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
                if (HEADER_LOG.isDebugEnabled()) {
                    for (int i = 0; i < headers.size(); i++) {
                        HEADER_LOG.debug("{} >> {}", id, headers.get(i));
                    }
                }
            }

            @Override
            public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
                if (FRAME_LOG.isDebugEnabled()) {
                    logFrameInfo(id + " <<", frame);
                }
                if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
                    logFramePayload(id + " <<", frame);
                }
            }

            @Override
            public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
                if (FRAME_LOG.isDebugEnabled()) {
                    logFrameInfo(id + " >>", frame);
                }
                if (FRAME_PAYLOAD_LOG.isDebugEnabled()) {
                    logFramePayload(id + " >>", frame);
                }
            }

            @Override
            public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
                if (FLOW_CTRL_LOG.isDebugEnabled()) {
                    logFlowControl(id + " <<", streamId, delta, actualSize);
                }
            }

            @Override
            public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
                if (FLOW_CTRL_LOG.isDebugEnabled()) {
                    logFlowControl(id + " >>", streamId, delta, actualSize);
                }
            }
        });
    } else {
        http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor, h1Config, charCodingConfig, http1ConnectionReuseStrategy, http1ResponseParserFactory, http1RequestWriterFactory, null);
        http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor, exchangeHandlerFactory, h2Config, charCodingConfig, null);
    }
    ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ClientHttp1UpgradeHandler(http1StreamHandlerFactory));
    ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ClientH2UpgradeHandler(http2StreamHandlerFactory));
    final HttpVersionPolicy versionPolicy = attachment instanceof HttpVersionPolicy ? (HttpVersionPolicy) attachment : HttpVersionPolicy.NEGOTIATE;
    switch(versionPolicy) {
        case FORCE_HTTP_2:
            return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
        case FORCE_HTTP_1:
            return new ClientHttp1IOEventHandler(http1StreamHandlerFactory.create(ioSession));
        default:
            return new HttpProtocolNegotiator(ioSession, null);
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) FramePrinter(org.apache.hc.core5.http2.frame.FramePrinter) HttpConnection(org.apache.hc.core5.http.HttpConnection) ClientH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) ClientH2PrefaceHandler(org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler) Header(org.apache.hc.core5.http.Header) ClientHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) HttpProtocolNegotiator(org.apache.hc.core5.http2.impl.nio.HttpProtocolNegotiator) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) ClientH2UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ClientH2UpgradeHandler) List(java.util.List) ClientHttp1UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ClientHttp1UpgradeHandler) ClientHttp1IOEventHandler(org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandler)

Example 22 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.

the class LoggingHttp1StreamListener method onRequestHead.

@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
    if (headerLog.isDebugEnabled()) {
        final String idRequestDirection = LoggingSupport.getId(connection) + requestDirection;
        headerLog.debug("{}{}", idRequestDirection, new RequestLine(request));
        for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
            headerLog.debug("{}{}", idRequestDirection, it.next());
        }
    }
}
Also used : RequestLine(org.apache.hc.core5.http.message.RequestLine) Header(org.apache.hc.core5.http.Header)

Example 23 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection in project httpcomponents-core by apache.

the class AsyncFullDuplexServerExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).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)");
            }
        }
    }).register("/echo", () -> new AsyncServerExchangeHandler() {

        ByteBuffer buffer = ByteBuffer.allocate(2048);

        CapacityChannel inputCapacityChannel;

        DataStreamChannel outputDataChannel;

        boolean endStream;

        private void ensureCapacity(final int chunk) {
            if (buffer.remaining() < chunk) {
                final ByteBuffer oldBuffer = buffer;
                oldBuffer.flip();
                buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
                buffer.put(oldBuffer);
            }
        }

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
            responseChannel.sendResponse(response, entityDetails, context);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.write(src);
                }
            }
            if (src.hasRemaining()) {
                ensureCapacity(src.remaining());
                buffer.put(src);
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            if (buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
                inputCapacityChannel = null;
            } else {
                inputCapacityChannel = capacityChannel;
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws IOException {
            endStream = true;
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.endStream();
                }
            } else {
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public int available() {
            return buffer.position();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            outputDataChannel = channel;
            buffer.flip();
            if (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            buffer.compact();
            if (buffer.position() == 0 && endStream) {
                channel.endStream();
            }
            final CapacityChannel capacityChannel = inputCapacityChannel;
            if (capacityChannel != null && buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
            }
        }

        @Override
        public void failed(final Exception cause) {
            if (!(cause instanceof SocketException)) {
                cause.printStackTrace(System.out);
            }
        }

        @Override
        public void releaseResources() {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP server shutting down");
        server.close(CloseMode.GRACEFUL);
    }));
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    final ListenerEndpoint listenerEndpoint = future.get();
    System.out.print("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) SocketException(java.net.SocketException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint)

Example 24 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection 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 25 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection 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)

Aggregations

HttpConnection (org.apache.hc.core5.http.HttpConnection)40 HttpResponse (org.apache.hc.core5.http.HttpResponse)19 Test (org.junit.jupiter.api.Test)17 HttpRequest (org.apache.hc.core5.http.HttpRequest)15 Header (org.apache.hc.core5.http.Header)14 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)13 HttpAsyncRequester (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 HttpHost (org.apache.hc.core5.http.HttpHost)11 RequestLine (org.apache.hc.core5.http.message.RequestLine)11 StatusLine (org.apache.hc.core5.http.message.StatusLine)11 RawFrame (org.apache.hc.core5.http2.frame.RawFrame)11 H2StreamListener (org.apache.hc.core5.http2.impl.nio.H2StreamListener)11 List (java.util.List)10 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)10 IOException (java.io.IOException)9 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)9 Message (org.apache.hc.core5.http.Message)8 HttpException (org.apache.hc.core5.http.HttpException)7 AsyncClientEndpoint (org.apache.hc.core5.http.nio.AsyncClientEndpoint)7