Search in sources :

Example 11 with Http1StreamListener

use of org.apache.hc.core5.http.impl.Http1StreamListener 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 12 with Http1StreamListener

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

the class ClassicPostExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final HttpRequester httpRequester = RequesterBootstrap.bootstrap().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)");
            }
        }
    }).setSocketConfig(SocketConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).create();
    final HttpCoreContext coreContext = HttpCoreContext.create();
    final HttpHost target = new HttpHost("httpbin.org");
    final HttpEntity[] requestBodies = { HttpEntities.create("This is the first test request", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the second test request".getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM), HttpEntities.create(outStream -> outStream.write(("This is the third test request " + "(streaming)").getBytes(StandardCharsets.UTF_8)), ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the fourth test request " + "(streaming with trailers)", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8), new BasicHeader("trailer1", "And goodbye")) };
    final String requestUri = "/post";
    for (int i = 0; i < requestBodies.length; i++) {
        final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
        request.setEntity(requestBodies[i]);
        try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
            System.out.println(requestUri + "->" + response.getCode());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
        }
    }
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester) ClassicRequestBuilder(org.apache.hc.core5.http.io.support.ClassicRequestBuilder) RequesterBootstrap(org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) RequestLine(org.apache.hc.core5.http.message.RequestLine) Timeout(org.apache.hc.core5.util.Timeout) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) HttpRequest(org.apache.hc.core5.http.HttpRequest) ContentType(org.apache.hc.core5.http.ContentType) HttpConnection(org.apache.hc.core5.http.HttpConnection) HttpEntities(org.apache.hc.core5.http.io.entity.HttpEntities) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) EntityUtils(org.apache.hc.core5.http.io.entity.EntityUtils) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 13 with Http1StreamListener

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

the class ClassicReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port]");
        System.exit(1);
    }
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    System.out.println("Reverse proxy to " + targetHost);
    final HttpRequester requester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[proxy->origin] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setConnPoolListener(new ConnPoolListener<HttpHost>() {

        @Override
        public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection leased ").append(route);
            System.out.println(buf);
        }

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection released ").append(route);
            final PoolStats totals = connPoolStats.getTotalStats();
            buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
            buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
            buf.append(" of ").append(totals.getMax());
            System.out.println(buf);
        }
    }).create();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[client->proxy] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setExceptionListener(new ExceptionListener() {

        @Override
        public void onError(final Exception ex) {
            if (ex instanceof SocketException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }

        @Override
        public void onError(final HttpConnection connection, final Exception ex) {
            if (ex instanceof SocketTimeoutException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " time out");
            } else if (ex instanceof SocketException || ex instanceof ConnectionClosedException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }
    }).register("*", new ProxyHandler(targetHost, requester)).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) SocketTimeoutException(java.net.SocketTimeoutException) HttpHost(org.apache.hc.core5.http.HttpHost) ConnPoolListener(org.apache.hc.core5.pool.ConnPoolListener) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) ExceptionListener(org.apache.hc.core5.http.ExceptionListener) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester)

Example 14 with Http1StreamListener

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

the class ReactiveFullDuplexServerExample 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 ReactiveServerExchangeHandler((request, entityDetails, responseChannel, context, requestBody, responseBodyFuture) -> {
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        responseChannel.sendResponse(new BasicHttpResponse(200), new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), context);
        // Simply using the request publisher as the response publisher will
        // cause the server to echo the request body.
        responseBodyFuture.execute(requestBody);
    })).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.ofDays(Long.MAX_VALUE));
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ReactiveServerExchangeHandler(org.apache.hc.core5.reactive.ReactiveServerExchangeHandler) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) 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) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 15 with Http1StreamListener

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

the class HttpBenchmark method execute.

public Results execute() throws Exception {
    final HttpProcessorBuilder builder = HttpProcessorBuilder.create().addAll(new H2RequestContent(), new H2RequestTargetHost(), new H2RequestConnControl(), new RequestUserAgent("HttpCore-AB/5.0"));
    if (this.config.isUseExpectContinue()) {
        builder.add(new RequestExpectContinue());
    }
    final SSLContext sslContext;
    if ("https".equals(config.getUri().getScheme())) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.setProtocol("SSL");
        if (config.isDisableSSLVerification()) {
            sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true);
        } else if (config.getTrustStorePath() != null) {
            sslContextBuilder.loadTrustMaterial(new File(config.getTrustStorePath()), config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray() : null);
        }
        if (config.getIdentityStorePath() != null) {
            sslContextBuilder.loadKeyMaterial(Paths.get(config.getIdentityStorePath()), config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null, config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray() : null);
        }
        sslContext = sslContextBuilder.build();
    } else {
        sslContext = SSLContexts.createSystemDefault();
    }
    final HttpVersionPolicy versionPolicy;
    if (config.isForceHttp2()) {
        versionPolicy = HttpVersionPolicy.FORCE_HTTP_2;
    } else {
        if (sslContext != null) {
            versionPolicy = HttpVersionPolicy.NEGOTIATE;
        } else {
            versionPolicy = HttpVersionPolicy.FORCE_HTTP_1;
        }
    }
    final Stats stats = new Stats();
    try (final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setHttpProcessor(builder.build()).setTlsStrategy(new BasicClientTlsStrategy(sslContext)).setVersionPolicy(versionPolicy).setH2Config(H2Config.custom().setPushEnabled(false).build()).setIOSessionDecorator(ioSession -> new IOSession() {

        @Override
        public String getId() {
            return ioSession.getId();
        }

        @Override
        public Lock getLock() {
            return ioSession.getLock();
        }

        @Override
        public void enqueue(final Command command, final Command.Priority priority) {
            ioSession.enqueue(command, priority);
        }

        @Override
        public boolean hasCommands() {
            return ioSession.hasCommands();
        }

        @Override
        public Command poll() {
            return ioSession.poll();
        }

        @Override
        public ByteChannel channel() {
            return ioSession.channel();
        }

        @Override
        public SocketAddress getRemoteAddress() {
            return ioSession.getRemoteAddress();
        }

        @Override
        public SocketAddress getLocalAddress() {
            return ioSession.getLocalAddress();
        }

        @Override
        public int getEventMask() {
            return ioSession.getEventMask();
        }

        @Override
        public void setEventMask(final int ops) {
            ioSession.setEventMask(ops);
        }

        @Override
        public void setEvent(final int op) {
            ioSession.setEvent(op);
        }

        @Override
        public void clearEvent(final int op) {
            ioSession.clearEvent(op);
        }

        @Override
        public void close() {
            ioSession.close();
        }

        @Override
        public Status getStatus() {
            return ioSession.getStatus();
        }

        @Override
        public int read(final ByteBuffer dst) throws IOException {
            final int bytesRead = ioSession.read(dst);
            if (bytesRead > 0) {
                stats.incTotalBytesRecv(bytesRead);
            }
            return bytesRead;
        }

        @Override
        public int write(final ByteBuffer src) throws IOException {
            final int bytesWritten = ioSession.write(src);
            if (bytesWritten > 0) {
                stats.incTotalBytesSent(bytesWritten);
            }
            return bytesWritten;
        }

        @Override
        public boolean isOpen() {
            return ioSession.isOpen();
        }

        @Override
        public Timeout getSocketTimeout() {
            return ioSession.getSocketTimeout();
        }

        @Override
        public void setSocketTimeout(final Timeout timeout) {
            ioSession.setSocketTimeout(timeout);
        }

        @Override
        public long getLastReadTime() {
            return ioSession.getLastReadTime();
        }

        @Override
        public long getLastWriteTime() {
            return ioSession.getLastWriteTime();
        }

        @Override
        public long getLastEventTime() {
            return ioSession.getLastEventTime();
        }

        @Override
        public void updateReadTime() {
            ioSession.updateReadTime();
        }

        @Override
        public void updateWriteTime() {
            ioSession.updateWriteTime();
        }

        @Override
        public void close(final CloseMode closeMode) {
            ioSession.close(closeMode);
        }

        @Override
        public IOEventHandler getHandler() {
            return ioSession.getHandler();
        }

        @Override
        public void upgrade(final IOEventHandler handler) {
            ioSession.upgrade(handler);
        }
    }).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            if (config.getVerbosity() >= 3) {
                System.out.println(">> " + request.getMethod() + " " + request.getRequestUri());
                final Header[] headers = request.getHeaders();
                for (final Header header : headers) {
                    System.out.println(">> " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            if (config.getVerbosity() >= 3) {
                System.out.println("<< " + response.getCode() + " " + response.getReasonPhrase());
                final Header[] headers = response.getHeaders();
                for (final Header header : headers) {
                    System.out.println("<< " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
        }
    }).setStreamListener(new H2StreamListener() {

        private final FramePrinter framePrinter = new FramePrinter();

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            if (config.getVerbosity() >= 3) {
                for (final Header header : headers) {
                    System.out.println("<< " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            if (config.getVerbosity() >= 3) {
                for (final Header header : headers) {
                    System.out.println(">> " + header);
                }
                System.out.println();
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
            if (config.getVerbosity() >= 4) {
                System.out.print("<< ");
                try {
                    framePrinter.printFrameInfo(frame, System.out);
                    System.out.println();
                    if (!frame.isType(FrameType.DATA)) {
                        framePrinter.printPayload(frame, System.out);
                        System.out.println();
                    }
                } catch (final IOException ignore) {
                }
            }
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
            if (config.getVerbosity() >= 4) {
                System.out.print(">> ");
                try {
                    framePrinter.printFrameInfo(frame, System.out);
                    System.out.println();
                    if (!frame.isType(FrameType.DATA)) {
                        framePrinter.printPayload(frame, System.out);
                        System.out.println();
                    }
                } catch (final IOException ignore) {
                }
            }
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
            if (config.getVerbosity() >= 5) {
                System.out.println("<< stream " + streamId + ": " + actualSize + " " + delta);
            }
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
            if (config.getVerbosity() >= 5) {
                System.out.println(">> stream " + streamId + ": " + actualSize + " " + delta);
            }
        }
    }).setIOReactorConfig(IOReactorConfig.custom().setSoTimeout(config.getSocketTimeout()).build()).create()) {
        requester.setDefaultMaxPerRoute(config.getConcurrencyLevel());
        requester.setMaxTotal(config.getConcurrencyLevel() * 2);
        requester.start();
        return doExecute(requester, stats);
    }
}
Also used : HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) H2RequestContent(org.apache.hc.core5.http2.protocol.H2RequestContent) H2RequestConnControl(org.apache.hc.core5.http2.protocol.H2RequestConnControl) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) IOSession(org.apache.hc.core5.reactor.IOSession) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) SocketAddress(java.net.SocketAddress) SSLContextBuilder(org.apache.hc.core5.ssl.SSLContextBuilder) HttpRequest(org.apache.hc.core5.http.HttpRequest) FramePrinter(org.apache.hc.core5.http2.frame.FramePrinter) RequestExpectContinue(org.apache.hc.core5.http.protocol.RequestExpectContinue) RequestUserAgent(org.apache.hc.core5.http.protocol.RequestUserAgent) Timeout(org.apache.hc.core5.util.Timeout) HttpResponse(org.apache.hc.core5.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Lock(java.util.concurrent.locks.Lock) IOEventHandler(org.apache.hc.core5.reactor.IOEventHandler) HttpProcessorBuilder(org.apache.hc.core5.http.protocol.HttpProcessorBuilder) ByteChannel(java.nio.channels.ByteChannel) BasicClientTlsStrategy(org.apache.hc.core5.http.nio.ssl.BasicClientTlsStrategy) Header(org.apache.hc.core5.http.Header) Command(org.apache.hc.core5.reactor.Command) CloseMode(org.apache.hc.core5.io.CloseMode) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2RequestTargetHost(org.apache.hc.core5.http2.protocol.H2RequestTargetHost) File(java.io.File)

Aggregations

Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)14 HttpRequest (org.apache.hc.core5.http.HttpRequest)13 HttpResponse (org.apache.hc.core5.http.HttpResponse)13 HttpConnection (org.apache.hc.core5.http.HttpConnection)12 HttpHost (org.apache.hc.core5.http.HttpHost)9 RequestLine (org.apache.hc.core5.http.message.RequestLine)9 StatusLine (org.apache.hc.core5.http.message.StatusLine)9 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)8 HttpAsyncRequester (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)7 Header (org.apache.hc.core5.http.Header)6 Timeout (org.apache.hc.core5.util.Timeout)6 IOException (java.io.IOException)5 ByteBuffer (java.nio.ByteBuffer)5 List (java.util.List)5 HttpException (org.apache.hc.core5.http.HttpException)5 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)5 InetSocketAddress (java.net.InetSocketAddress)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 Message (org.apache.hc.core5.http.Message)4 HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)4