Search in sources :

Example 51 with Args

use of org.apache.hc.core5.util.Args 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 52 with Args

use of org.apache.hc.core5.util.Args 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 53 with Args

use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.

the class AsyncServerFilterExample 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).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractAsyncServerAuthFilter<String>(true) {

        @Override
        protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
            return authorizationValue;
        }

        @Override
        protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "let me pass".equals(challengeResponse);
        }

        @Override
        protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "who goes there?";
        }
    }).addFilterFirst("my-filter", (request, entityDetails, context, responseTrigger, chain) -> {
        if (request.getRequestUri().equals("/back-door")) {
            responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_OK), AsyncEntityProducers.create("Welcome"));
            return null;
        }
        return chain.proceed(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {

            @Override
            public void sendInformation(final HttpResponse response) throws HttpException, IOException {
                responseTrigger.sendInformation(response);
            }

            @Override
            public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
                response.addHeader("X-Filter", "My-Filter");
                responseTrigger.submitResponse(response, entityProducer);
            }

            @Override
            public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
                responseTrigger.pushPromise(promise, responseProducer);
            }
        });
    }).register("*", new AsyncServerRequestHandler<Message<HttpRequest, String>>() {

        @Override
        public AsyncRequestConsumer<Message<HttpRequest, String>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
        }

        @Override
        public void handle(final Message<HttpRequest, String> requestMessage, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            // do something useful
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hello").build(), context);
        }
    }).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 : URIAuthority(org.apache.hc.core5.net.URIAuthority) Message(org.apache.hc.core5.http.Message) BasicRequestConsumer(org.apache.hc.core5.http.nio.support.BasicRequestConsumer) InetSocketAddress(java.net.InetSocketAddress) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncFilterChain(org.apache.hc.core5.http.nio.AsyncFilterChain) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) IOException(java.io.IOException) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) AbstractAsyncServerAuthFilter(org.apache.hc.core5.http.nio.support.AbstractAsyncServerAuthFilter)

Example 54 with Args

use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.

the class ClassicFileServerExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);
    }
    // Document root directory
    final String docRoot = args[0];
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    SSLContext sslContext = null;
    if (port == 8443) {
        // Initialize SSL context
        final URL url = ClassicFileServerExample.class.getResource("/my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        sslContext = SSLContexts.custom().loadKeyMaterial(url, "secret".toCharArray(), "secret".toCharArray()).build();
    }
    final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).setSslContext(sslContext).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 HttpFileHandler(docRoot)).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpConnection(org.apache.hc.core5.http.HttpConnection) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) MethodNotSupportedException(org.apache.hc.core5.http.MethodNotSupportedException) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SocketTimeoutException(java.net.SocketTimeoutException) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) ExceptionListener(org.apache.hc.core5.http.ExceptionListener)

Example 55 with Args

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

Aggregations

HttpHost (org.apache.hc.core5.http.HttpHost)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)25 HttpResponse (org.apache.hc.core5.http.HttpResponse)24 StatusLine (org.apache.hc.core5.http.message.StatusLine)22 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)22 IOException (java.io.IOException)21 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)19 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)19 HttpConnection (org.apache.hc.core5.http.HttpConnection)19 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)17 Header (org.apache.hc.core5.http.Header)17 HttpException (org.apache.hc.core5.http.HttpException)16 CountDownLatch (java.util.concurrent.CountDownLatch)13 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)13 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)12 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)12 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)12 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)12 EntityDetails (org.apache.hc.core5.http.EntityDetails)11 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)11