Search in sources :

Example 51 with BasicHttpRequest

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

the class Http1IntegrationTest method testSlowResponseConsumer.

@Test
public void testSlowResponseConsumer() throws Exception {
    server.register("/", () -> new MultiLineResponseHandler("0123456789abcd", 100));
    final InetSocketAddress serverEndpoint = server.start();
    client.start(Http1Config.custom().setBufferSize(256).build());
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(new AbstractClassicEntityConsumer<String>(16, Executors.newSingleThreadExecutor()) {

        @Override
        protected String consumeData(final ContentType contentType, final InputStream inputStream) throws IOException {
            final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
            final StringBuilder buffer = new StringBuilder();
            try {
                final byte[] tmp = new byte[16];
                int l;
                while ((l = inputStream.read(tmp)) != -1) {
                    buffer.append(charset.decode(ByteBuffer.wrap(tmp, 0, l)));
                    Thread.sleep(50);
                }
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException(ex.getMessage());
            }
            return buffer.toString();
        }
    }), null);
    final Message<HttpResponse, String> result1 = future1.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    final String s1 = result1.getBody();
    Assertions.assertNotNull(s1);
    final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("0123456789abcd", t1.nextToken());
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) InterruptedIOException(java.io.InterruptedIOException) Message(org.apache.hc.core5.http.Message) ContentType(org.apache.hc.core5.http.ContentType) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AbstractClassicEntityConsumer(org.apache.hc.core5.http.nio.support.classic.AbstractClassicEntityConsumer) StringTokenizer(java.util.StringTokenizer) Test(org.junit.Test)

Example 52 with BasicHttpRequest

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

the class H2CompatibilityTest method executeH2.

void executeH2(final HttpHost target) throws Exception {
    {
        System.out.println("*** HTTP/2 simple request execution ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
        try {
            final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
            endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> responseMessage) {
                    final HttpResponse response = responseMessage.getHead();
                    final int code = response.getCode();
                    if (code == HttpStatus.SC_OK) {
                        logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
                    } else {
                        logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
            if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                logResult(TestResult.NOK, target, null, null, "(single request execution failed to complete in time)");
            }
        } catch (final ExecutionException ex) {
            final Throwable cause = ex.getCause();
            logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
        } catch (final TimeoutException ex) {
            logResult(TestResult.NOK, target, null, null, "(time out)");
        }
    }
    {
        System.out.println("*** HTTP/2 multiplexed request execution ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
        try {
            final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
            final int reqCount = 20;
            final CountDownLatch countDownLatch = new CountDownLatch(reqCount);
            for (int i = 0; i < reqCount; i++) {
                final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
                endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

                    @Override
                    public void completed(final Message<HttpResponse, String> responseMessage) {
                        final HttpResponse response = responseMessage.getHead();
                        final int code = response.getCode();
                        if (code == HttpStatus.SC_OK) {
                            logResult(TestResult.OK, target, httpget, response, "multiplexed / " + response.getFirstHeader("server"));
                        } else {
                            logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
                        }
                        countDownLatch.countDown();
                    }

                    @Override
                    public void failed(final Exception ex) {
                        logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
                        countDownLatch.countDown();
                    }

                    @Override
                    public void cancelled() {
                        logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
                        countDownLatch.countDown();
                    }
                });
            }
            if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                logResult(TestResult.NOK, target, null, null, "(multiplexed request execution failed to complete in time)");
            }
        } catch (final ExecutionException ex) {
            final Throwable cause = ex.getCause();
            logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
        } catch (final TimeoutException ex) {
            logResult(TestResult.NOK, target, null, null, "(time out)");
        }
    }
    {
        System.out.println("*** HTTP/2 request execution with push ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
        try {
            final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
            final CountDownLatch countDownLatch = new CountDownLatch(5);
            final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/index.html");
            final Future<Message<HttpResponse, String>> future = endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, Void>>(new BasicResponseConsumer<>(new DiscardingEntityConsumer<>())) {

                @Override
                protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, Void> responseMessage) throws IOException, HttpException {
                    final HttpResponse response = responseMessage.getHead();
                    logResult(TestResult.OK, target, promise, response, "pushed / " + response.getFirstHeader("server"));
                    countDownLatch.countDown();
                }

                @Override
                protected void handleError(final HttpRequest promise, final Exception cause) {
                    logResult(TestResult.NOK, target, promise, null, "(" + cause.getMessage() + ")");
                    countDownLatch.countDown();
                }
            }, null, null);
            final Message<HttpResponse, String> message = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
            final HttpResponse response = message.getHead();
            final int code = response.getCode();
            if (code == HttpStatus.SC_OK) {
                logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
                if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                    logResult(TestResult.NOK, target, null, null, "Push messages not received");
                }
            } else {
                logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
            }
        } catch (final ExecutionException ex) {
            final Throwable cause = ex.getCause();
            logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
        } catch (final TimeoutException ex) {
            logResult(TestResult.NOK, target, null, null, "(time out)");
        }
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Arrays(java.util.Arrays) H2Config(org.apache.hc.core5.http2.config.H2Config) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) LoggingConnPoolListener(org.apache.hc.core5.testing.classic.LoggingConnPoolListener) TimeoutException(java.util.concurrent.TimeoutException) AbstractAsyncPushHandler(org.apache.hc.core5.http.nio.support.AbstractAsyncPushHandler) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) LoggingIOSessionListener(org.apache.hc.core5.testing.nio.LoggingIOSessionListener) TextUtils(org.apache.hc.core5.util.TextUtils) Future(java.util.concurrent.Future) LoggingHttp1StreamListener(org.apache.hc.core5.testing.nio.LoggingHttp1StreamListener) CodingErrorAction(java.nio.charset.CodingErrorAction) CloseMode(org.apache.hc.core5.io.CloseMode) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpException(org.apache.hc.core5.http.HttpException) Message(org.apache.hc.core5.http.Message) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) LoggingH2StreamListener(org.apache.hc.core5.testing.nio.LoggingH2StreamListener) H2RequesterBootstrap(org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) IOException(java.io.IOException) LoggingIOSessionDecorator(org.apache.hc.core5.testing.nio.LoggingIOSessionDecorator) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) Timeout(org.apache.hc.core5.util.Timeout) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) HttpHost(org.apache.hc.core5.http.HttpHost) LoggingExceptionCallback(org.apache.hc.core5.testing.nio.LoggingExceptionCallback) HttpRequest(org.apache.hc.core5.http.HttpRequest) ContentType(org.apache.hc.core5.http.ContentType) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) Method(org.apache.hc.core5.http.Method) HttpStatus(org.apache.hc.core5.http.HttpStatus) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractAsyncPushHandler(org.apache.hc.core5.http.nio.support.AbstractAsyncPushHandler) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) TimeoutException(java.util.concurrent.TimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) Future(java.util.concurrent.Future) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) TimeoutException(java.util.concurrent.TimeoutException)

Example 53 with BasicHttpRequest

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

the class H2CompatibilityTest method executeHttpBin.

void executeHttpBin(final HttpHost target) throws Exception {
    {
        System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***");
        final List<Message<HttpRequest, AsyncEntityProducer>> requestMessages = Arrays.asList(new Message<>(new BasicHttpRequest(Method.GET, target, "/headers"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.GET, target, "/drip"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)));
        for (final Message<HttpRequest, AsyncEntityProducer> message : requestMessages) {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            final HttpRequest request = message.getHead();
            final AsyncEntityProducer entityProducer = message.getBody();
            client.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), TIMEOUT, new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> responseMessage) {
                    final HttpResponse response = responseMessage.getHead();
                    final int code = response.getCode();
                    if (code == HttpStatus.SC_OK) {
                        logResult(TestResult.OK, target, request, response, Objects.toString(response.getFirstHeader("server")));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
            if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
            }
        }
    }
    {
        System.out.println("*** httpbin.org HTTP/1.1 pipelined request execution ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT);
        final AsyncClientEndpoint streamEndpoint = connectFuture.get();
        final int n = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            final HttpRequest request;
            final AsyncEntityProducer entityProducer;
            if (i % 2 == 0) {
                request = new BasicHttpRequest(Method.GET, target, "/headers");
                entityProducer = null;
            } else {
                request = new BasicHttpRequest(Method.POST, target, "/anything");
                entityProducer = new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN);
            }
            streamEndpoint.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> responseMessage) {
                    final HttpResponse response = responseMessage.getHead();
                    final int code = response.getCode();
                    if (code == HttpStatus.SC_OK) {
                        logResult(TestResult.OK, target, request, response, "pipelined / " + response.getFirstHeader("server"));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
        }
        if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
            logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
        }
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) TimeoutException(java.util.concurrent.TimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Future(java.util.concurrent.Future) List(java.util.List) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 54 with BasicHttpRequest

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

the class H2IntegrationTest method testSlowResponseProducer.

@Test
public void testSlowResponseProducer() throws Exception {
    server.register("*", () -> new AbstractClassicServerExchangeHandler(2048, Executors.newSingleThreadExecutor()) {

        @Override
        protected void handle(final HttpRequest request, final InputStream requestStream, final HttpResponse response, final OutputStream responseStream, final HttpContext context) throws IOException, HttpException {
            if (!"/hello".equals(request.getPath())) {
                response.setCode(HttpStatus.SC_NOT_FOUND);
                return;
            }
            if (!Method.POST.name().equalsIgnoreCase(request.getMethod())) {
                response.setCode(HttpStatus.SC_NOT_IMPLEMENTED);
                return;
            }
            if (requestStream == null) {
                return;
            }
            final Header h1 = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
            final ContentType contentType = h1 != null ? ContentType.parse(h1.getValue()) : null;
            final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
            response.setCode(HttpStatus.SC_OK);
            response.setHeader(h1);
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, charset));
                final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(responseStream, charset))) {
                try {
                    String l;
                    int count = 0;
                    while ((l = reader.readLine()) != null) {
                        writer.write(l);
                        writer.write("\r\n");
                        count++;
                        if (count % 500 == 0) {
                            Thread.sleep(500);
                        }
                    }
                    writer.flush();
                } catch (final InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new InterruptedIOException(ex.getMessage());
                }
            }
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start(H2Config.custom().setInitialWindowSize(512).build());
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/hello"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcd", 2000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    final String s1 = result1.getBody();
    Assertions.assertNotNull(s1);
    final StringTokenizer t1 = new StringTokenizer(s1, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("0123456789abcd", t1.nextToken());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ContentType(org.apache.hc.core5.http.ContentType) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BufferedWriter(java.io.BufferedWriter) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) Charset(java.nio.charset.Charset) AbstractClassicServerExchangeHandler(org.apache.hc.core5.http.nio.support.classic.AbstractClassicServerExchangeHandler) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) Header(org.apache.hc.core5.http.Header) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Test(org.junit.Test)

Example 55 with BasicHttpRequest

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

the class H2IntegrationTest method testPush.

@Test
public void testPush() throws Exception {
    final InetSocketAddress serverEndpoint = server.start();
    server.register("/hello", () -> new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {

        @Override
        protected void handle(final Message<HttpRequest, Void> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")), context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)));
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hi there", ContentType.TEXT_PLAIN).build(), context);
        }
    });
    client.start(H2Config.custom().setPushEnabled(true).build());
    final BlockingQueue<Message<HttpResponse, String>> pushMessageQueue = new LinkedBlockingDeque<>();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, String>>(new BasicResponseConsumer<>(new StringAsyncEntityConsumer())) {

        @Override
        protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, String> responseMessage) throws IOException, HttpException {
            try {
                pushMessageQueue.put(responseMessage);
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException(ex.getMessage());
            }
        }
    }, null, null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    final String entity1 = result1.getBody();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    Assertions.assertEquals("Hi there", entity1);
    final Message<HttpResponse, String> result2 = pushMessageQueue.poll(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result2);
    final HttpResponse response2 = result2.getHead();
    final String entity2 = result2.getBody();
    Assertions.assertEquals(200, response2.getCode());
    Assertions.assertNotNull(entity2);
    final StringTokenizer t1 = new StringTokenizer(entity2, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("Pushing lots of stuff", t1.nextToken());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicPushProducer(org.apache.hc.core5.http.nio.support.BasicPushProducer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) StringTokenizer(java.util.StringTokenizer) Test(org.junit.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)45 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