Search in sources :

Example 16 with HttpConnection

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

the class AsyncFullDuplexClientExample 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
    // Disable 'Expect: Continue' handshake some servers cannot handle well
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setHttpProcessor(HttpProcessors.customClient(null).addLast((HttpRequestInterceptor) (request, entity, context) -> request.removeHeaders(HttpHeaders.EXPECT)).build()).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 URI requestUri = new URI("http://httpbin.org/post");
    final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    final CountDownLatch latch = new CountDownLatch(1);
    requester.execute(new AsyncClientExchangeHandler() {

        @Override
        public void releaseResources() {
            requestProducer.releaseResources();
            responseConsumer.releaseResources();
            latch.countDown();
        }

        @Override
        public void cancel() {
            System.out.println(requestUri + " cancelled");
        }

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

        @Override
        public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
            requestProducer.sendRequest(channel, httpContext);
        }

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

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            requestProducer.produce(channel);
        }

        @Override
        public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
            responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
        }

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

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

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            responseConsumer.streamEnd(trailers);
        }
    }, Timeout.ofSeconds(30), HttpCoreContext.create());
    latch.await(1, TimeUnit.MINUTES);
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) AsyncRequestBuilder(org.apache.hc.core5.http.nio.support.AsyncRequestBuilder) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncRequesterBootstrap(org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap) RequestLine(org.apache.hc.core5.http.message.RequestLine) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) ByteBuffer(java.nio.ByteBuffer) EntityDetails(org.apache.hc.core5.http.EntityDetails) StatusLine(org.apache.hc.core5.http.message.StatusLine) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpProcessors(org.apache.hc.core5.http.impl.HttpProcessors) CloseMode(org.apache.hc.core5.io.CloseMode) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) HttpResponse(org.apache.hc.core5.http.HttpResponse) URI(java.net.URI) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpException(org.apache.hc.core5.http.HttpException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) Header(org.apache.hc.core5.http.Header) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) IOException(java.io.IOException) Timeout(org.apache.hc.core5.util.Timeout) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) List(java.util.List) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) HttpRequestInterceptor(org.apache.hc.core5.http.HttpRequestInterceptor) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) URI(java.net.URI) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) 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) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 17 with HttpConnection

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

the class AsyncReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port] [--quiet]");
        System.exit(1);
    }
    // Target host
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    for (final String s : args) {
        if ("--quiet".equalsIgnoreCase(s)) {
            quiet = true;
            break;
        }
    }
    println("Reverse proxy to " + targetHost);
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(1, TimeUnit.MINUTES).build();
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(config).setConnPoolListener(new ConnPoolListener<HttpHost>() {

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

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] 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());
            println(buf.toString());
        }
    }).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[proxy<-origin] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).setMaxTotal(100).setDefaultMaxPerRoute(20).create();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[client<-proxy] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).register("*", () -> new IncomingExchangeHandler(targetHost, requester)).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        println("Reverse proxy shutting down");
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    server.start();
    server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    println("Listening on port " + port);
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 18 with HttpConnection

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

the class ClassicGetExecutionExample 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 String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    for (int i = 0; i < requestUris.length; i++) {
        final String requestUri = requestUris[i];
        final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
        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) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) 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)

Example 19 with HttpConnection

use of org.apache.hc.core5.http.HttpConnection in project JAuswertung by dennisfabri.

the class HttpServerPlugin method startUp.

boolean startUp() {
    try {
        state = true;
        final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
        httpServer = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).setExceptionListener(new ExceptionListener() {

            @Override
            public void onError(final Exception ex) {
                ex.printStackTrace();
            }

            @Override
            public void onError(final HttpConnection conn, final Exception ex) {
                if (ex instanceof SocketTimeoutException) {
                    System.err.println("Connection timed out");
                } else if (ex instanceof ConnectionClosedException) {
                    System.err.println(ex.getMessage());
                } else {
                    ex.printStackTrace();
                }
            }
        }).register("*", new DPRequestHandler(getDataProvider())).create();
        httpServer.start();
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                httpServer.close(CloseMode.GRACEFUL);
            }
        });
        httpServer.start();
        httpOptions.setEnabled(false);
        filter.setEnabled(source.getExportMode() == ExportMode.Filtered);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        DialogUtils.wichtigeMeldung(null, I18n.get("HttpServerNotStartet"));
        shutDown();
        httpServer = null;
        state = false;
        httpOptions.setEnabled(true);
        filter.setEnabled(false);
        return false;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpConnection(org.apache.hc.core5.http.HttpConnection) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) ExceptionListener(org.apache.hc.core5.http.ExceptionListener) SocketTimeoutException(java.net.SocketTimeoutException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException)

Example 20 with HttpConnection

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

the class H2AsyncClientProtocolStarter method createHandler.

@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
    if (HEADER_LOG.isDebugEnabled() || FRAME_LOG.isDebugEnabled() || FRAME_PAYLOAD_LOG.isDebugEnabled() || FLOW_CTRL_LOG.isDebugEnabled()) {
        final String id = ioSession.getId();
        final ClientH2StreamMultiplexerFactory 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);
                }
            }
        });
        return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
    }
    final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor, exchangeHandlerFactory, h2Config, charCodingConfig, null);
    return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
}
Also used : H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) FramePrinter(org.apache.hc.core5.http2.frame.FramePrinter) ClientH2PrefaceHandler(org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler) HttpConnection(org.apache.hc.core5.http.HttpConnection) ClientH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) IOException(java.io.IOException)

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