Search in sources :

Example 16 with RequestLine

use of org.apache.hc.core5.http.message.RequestLine 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 17 with RequestLine

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

the class ClassicPostExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final HttpRequester httpRequester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

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

Example 18 with RequestLine

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

the class TestBasicLineParser method testRLParse.

@Test
public void testRLParse() throws Exception {
    final CharArrayBuffer buf = new CharArrayBuffer(64);
    // typical request line
    buf.clear();
    buf.append("GET /stuff HTTP/1.1");
    RequestLine requestline = this.parser.parseRequestLine(buf);
    Assertions.assertEquals("GET /stuff HTTP/1.1", requestline.toString());
    Assertions.assertEquals(Method.GET.name(), requestline.getMethod());
    Assertions.assertEquals("/stuff", requestline.getUri());
    Assertions.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion());
    // Lots of blanks
    buf.clear();
    buf.append("  GET    /stuff   HTTP/1.1   ");
    requestline = this.parser.parseRequestLine(buf);
    Assertions.assertEquals("GET /stuff HTTP/1.1", requestline.toString());
    Assertions.assertEquals(Method.GET.name(), requestline.getMethod());
    Assertions.assertEquals("/stuff", requestline.getUri());
    Assertions.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion());
    // this is not strictly valid, but is lenient
    buf.clear();
    buf.append("\rGET /stuff HTTP/1.1");
    requestline = this.parser.parseRequestLine(buf);
    Assertions.assertEquals(Method.GET.name(), requestline.getMethod());
    Assertions.assertEquals("/stuff", requestline.getUri());
    Assertions.assertEquals(HttpVersion.HTTP_1_1, requestline.getProtocolVersion());
}
Also used : CharArrayBuffer(org.apache.hc.core5.util.CharArrayBuffer) Test(org.junit.jupiter.api.Test)

Example 19 with RequestLine

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

the class ReactiveFullDuplexServerExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).register("/echo", () -> new ReactiveServerExchangeHandler((request, entityDetails, responseChannel, context, requestBody, responseBodyFuture) -> {
        if (new BasicHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE).equals(request.getHeader(HttpHeaders.EXPECT))) {
            responseChannel.sendInformation(new BasicHttpResponse(100), context);
        }
        responseChannel.sendResponse(new BasicHttpResponse(200), new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), context);
        // Simply using the request publisher as the response publisher will
        // cause the server to echo the request body.
        responseBodyFuture.execute(requestBody);
    })).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP server shutting down");
        server.close(CloseMode.GRACEFUL);
    }));
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    final ListenerEndpoint listenerEndpoint = future.get();
    System.out.print("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.ofDays(Long.MAX_VALUE));
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) ReactiveServerExchangeHandler(org.apache.hc.core5.reactive.ReactiveServerExchangeHandler) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 20 with RequestLine

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

the class DefaultHttpRequestParser method createMessage.

@Override
protected T createMessage(final CharArrayBuffer buffer) throws HttpException {
    final RequestLine requestLine = getLineParser().parseRequestLine(buffer);
    final T request = this.requestFactory.newHttpRequest(requestLine.getMethod(), requestLine.getUri());
    request.setVersion(requestLine.getProtocolVersion());
    return request;
}
Also used : RequestLine(org.apache.hc.core5.http.message.RequestLine)

Aggregations

RequestLine (org.apache.hc.core5.http.message.RequestLine)16 HttpConnection (org.apache.hc.core5.http.HttpConnection)9 HttpRequest (org.apache.hc.core5.http.HttpRequest)9 HttpResponse (org.apache.hc.core5.http.HttpResponse)9 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)9 StatusLine (org.apache.hc.core5.http.message.StatusLine)9 Header (org.apache.hc.core5.http.Header)7 HttpHost (org.apache.hc.core5.http.HttpHost)5 HttpAsyncRequester (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)5 CountDownLatch (java.util.concurrent.CountDownLatch)4 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)4 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)4 ByteBuffer (java.nio.ByteBuffer)3 List (java.util.List)3 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)3 HttpException (org.apache.hc.core5.http.HttpException)3 Message (org.apache.hc.core5.http.Message)3 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)3 IOException (java.io.IOException)2 InetSocketAddress (java.net.InetSocketAddress)2