Search in sources :

Example 41 with BasicHttpRequest

use of org.apache.hc.core5.http.message.BasicHttpRequest in project mercury by yellow013.

the class AsyncClientFullDuplexExchange method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.NEGOTIATE, H2Config.DEFAULT, Http1Config.DEFAULT, ioReactorConfig);
    client.start();
    final BasicHttpRequest request = BasicRequestBuilder.post("http://httpbin.org/post").build();
    final BasicRequestProducer requestProducer = new BasicRequestProducer(request, new BasicAsyncEntityProducer("stuff", ContentType.TEXT_PLAIN));
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    System.out.println("Executing request " + request);
    final CountDownLatch latch = new CountDownLatch(1);
    client.execute(new AsyncClientExchangeHandler() {

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

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

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

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

        @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 context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
            responseConsumer.consumeResponse(response, entityDetails, context, 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);
        }
    });
    latch.await(1, TimeUnit.MINUTES);
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) MinimalHttpAsyncClient(org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) 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) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 42 with BasicHttpRequest

use of org.apache.hc.core5.http.message.BasicHttpRequest in project mercury by yellow013.

the class AsyncClientH2ServerPush method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final H2Config h2Config = H2Config.custom().setPushEnabled(true).build();
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setH2Config(h2Config).build();
    client.start();
    client.register("*", new Supplier<AsyncPushConsumer>() {

        @Override
        public AsyncPushConsumer get() {
            return new AbstractBinPushConsumer() {

                @Override
                protected void start(final HttpRequest promise, final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
                    System.out.println(promise.getPath() + " (push)->" + new StatusLine(response));
                }

                @Override
                protected int capacityIncrement() {
                    return Integer.MAX_VALUE;
                }

                @Override
                protected void data(final ByteBuffer data, final boolean endOfStream) throws IOException {
                }

                @Override
                protected void completed() {
                }

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

                @Override
                public void releaseResources() {
                }
            };
        }
    });
    final BasicHttpRequest request = BasicRequestBuilder.get("https://nghttp2.org/httpbin/").build();
    System.out.println("Executing request " + request);
    final Future<Void> future = client.execute(new BasicRequestProducer(request, null), new AbstractCharResponseConsumer<Void>() {

        @Override
        protected void start(final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
        }

        @Override
        protected int capacityIncrement() {
            return Integer.MAX_VALUE;
        }

        @Override
        protected void data(final CharBuffer data, final boolean endOfStream) throws IOException {
        }

        @Override
        protected Void buildResult() throws IOException {
            return null;
        }

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

        @Override
        public void releaseResources() {
        }
    }, null);
    future.get();
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : AsyncPushConsumer(org.apache.hc.core5.http.nio.AsyncPushConsumer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) AbstractBinPushConsumer(org.apache.hc.client5.http.async.methods.AbstractBinPushConsumer) ContentType(org.apache.hc.core5.http.ContentType) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) CharBuffer(java.nio.CharBuffer) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) HttpException(org.apache.hc.core5.http.HttpException) H2Config(org.apache.hc.core5.http2.config.H2Config)

Example 43 with BasicHttpRequest

use of org.apache.hc.core5.http.message.BasicHttpRequest in project mercury by yellow013.

the class AsyncClientHttpExchangeStreaming method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).build();
    client.start();
    final HttpHost target = new HttpHost("httpbin.org");
    final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    for (final String requestUri : requestUris) {
        final BasicHttpRequest request = BasicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
        System.out.println("Executing request " + request);
        final Future<Void> future = client.execute(new BasicRequestProducer(request, null), new AbstractCharResponseConsumer<Void>() {

            @Override
            protected void start(final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
                System.out.println(request + "->" + new StatusLine(response));
            }

            @Override
            protected int capacityIncrement() {
                return Integer.MAX_VALUE;
            }

            @Override
            protected void data(final CharBuffer data, final boolean endOfStream) throws IOException {
                while (data.hasRemaining()) {
                    System.out.print(data.get());
                }
                if (endOfStream) {
                    System.out.println();
                }
            }

            @Override
            protected Void buildResult() throws IOException {
                return null;
            }

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

            @Override
            public void releaseResources() {
            }
        }, null);
        future.get();
    }
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : ContentType(org.apache.hc.core5.http.ContentType) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) CharBuffer(java.nio.CharBuffer) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) HttpException(org.apache.hc.core5.http.HttpException)

Example 44 with BasicHttpRequest

use of org.apache.hc.core5.http.message.BasicHttpRequest in project meilisearch-java by meilisearch.

the class ApacheHttpClientTest method withException.

@Test
void withException() {
    reset(client);
    when(client.execute(any(), any(), any(), any(), any())).then(invocation -> {
        ((FutureCallback<SimpleHttpResponse>) invocation.getArgument(4)).failed(new Exception("BOOM!"));
        return CompletableFuture.completedFuture(null);
    });
    BasicHttpRequest request = new BasicHttpRequest(HttpMethod.GET, "/test", Collections.emptyMap(), "thisisabody");
    Exception exception = assertThrows(Exception.class, () -> classToTest.get(request), "");
    assertThat(findRootCause(exception).getClass(), equalTo(Exception.class));
}
Also used : FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) CancellationException(java.util.concurrent.CancellationException) BasicHttpRequest(com.meilisearch.sdk.http.request.BasicHttpRequest) Test(org.junit.jupiter.api.Test)

Example 45 with BasicHttpRequest

use of org.apache.hc.core5.http.message.BasicHttpRequest in project meilisearch-java by meilisearch.

the class ApacheHttpClientTest method withCancelledRequest.

@Test
void withCancelledRequest() {
    reset(client);
    when(client.execute(any(), any(), any(), any(), any())).then(invocation -> {
        ((FutureCallback<SimpleHttpResponse>) invocation.getArgument(4)).cancelled();
        return CompletableFuture.completedFuture(null);
    });
    BasicHttpRequest request = new BasicHttpRequest(HttpMethod.GET, "/test", Collections.emptyMap(), "thisisabody");
    Exception exception = assertThrows(Exception.class, () -> classToTest.get(request), "");
    assertThat(findRootCause(exception).getClass(), equalTo(CancellationException.class));
}
Also used : CancellationException(java.util.concurrent.CancellationException) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) BasicHttpRequest(com.meilisearch.sdk.http.request.BasicHttpRequest) CancellationException(java.util.concurrent.CancellationException) Test(org.junit.jupiter.api.Test)

Aggregations

HttpRequest (org.apache.hc.core5.http.HttpRequest)75 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)68 Test (org.junit.jupiter.api.Test)47 HttpResponse (org.apache.hc.core5.http.HttpResponse)41 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)37 Message (org.apache.hc.core5.http.Message)34 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)33 InetSocketAddress (java.net.InetSocketAddress)30 HttpHost (org.apache.hc.core5.http.HttpHost)30 Test (org.junit.Test)30 URI (java.net.URI)23 HttpException (org.apache.hc.core5.http.HttpException)21 IOException (java.io.IOException)20 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)19 URIAuthority (org.apache.hc.core5.net.URIAuthority)17 InterruptedIOException (java.io.InterruptedIOException)16 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)15 Header (org.apache.hc.core5.http.Header)14 URISyntaxException (java.net.URISyntaxException)8 ContentType (org.apache.hc.core5.http.ContentType)8