Search in sources :

Example 11 with RequestLine

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

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

the class LoggingHttp1StreamListener method onRequestHead.

@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
    if (headerLog.isDebugEnabled()) {
        final String idRequestDirection = LoggingSupport.getId(connection) + requestDirection;
        headerLog.debug("{}{}", idRequestDirection, new RequestLine(request));
        for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
            headerLog.debug("{}{}", idRequestDirection, it.next());
        }
    }
}
Also used : RequestLine(org.apache.hc.core5.http.message.RequestLine) Header(org.apache.hc.core5.http.Header)

Example 13 with RequestLine

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

the class BasicLineParser method parseRequestLine.

/**
 * Parses a request line.
 *
 * @param buffer    a buffer holding the line to parse
 *
 * @return  the parsed request line
 *
 * @throws ParseException        in case of a parse error
 */
@Override
public RequestLine parseRequestLine(final CharArrayBuffer buffer) throws ParseException {
    Args.notNull(buffer, "Char array buffer");
    final ParserCursor cursor = new ParserCursor(0, buffer.length());
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    final String method = this.tokenizer.parseToken(buffer, cursor, BLANKS);
    if (TextUtils.isEmpty(method)) {
        throw new ParseException("Invalid request line", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    final String uri = this.tokenizer.parseToken(buffer, cursor, BLANKS);
    if (TextUtils.isEmpty(uri)) {
        throw new ParseException("Invalid request line", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    final ProtocolVersion ver = parseProtocolVersion(buffer, cursor);
    this.tokenizer.skipWhiteSpace(buffer, cursor);
    if (!cursor.atEnd()) {
        throw new ParseException("Invalid request line", buffer, cursor.getLowerBound(), cursor.getUpperBound(), cursor.getPos());
    }
    return new RequestLine(method, uri, ver);
}
Also used : ParseException(org.apache.hc.core5.http.ParseException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 14 with RequestLine

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

the class AsyncFullDuplexServerExample 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 AsyncServerExchangeHandler() {

        ByteBuffer buffer = ByteBuffer.allocate(2048);

        CapacityChannel inputCapacityChannel;

        DataStreamChannel outputDataChannel;

        boolean endStream;

        private void ensureCapacity(final int chunk) {
            if (buffer.remaining() < chunk) {
                final ByteBuffer oldBuffer = buffer;
                oldBuffer.flip();
                buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
                buffer.put(oldBuffer);
            }
        }

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
            responseChannel.sendResponse(response, entityDetails, context);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.write(src);
                }
            }
            if (src.hasRemaining()) {
                ensureCapacity(src.remaining());
                buffer.put(src);
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            if (buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
                inputCapacityChannel = null;
            } else {
                inputCapacityChannel = capacityChannel;
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws IOException {
            endStream = true;
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.endStream();
                }
            } else {
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

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

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            outputDataChannel = channel;
            buffer.flip();
            if (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            buffer.compact();
            if (buffer.position() == 0 && endStream) {
                channel.endStream();
            }
            final CapacityChannel capacityChannel = inputCapacityChannel;
            if (capacityChannel != null && buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
            }
        }

        @Override
        public void failed(final Exception cause) {
            if (!(cause instanceof SocketException)) {
                cause.printStackTrace(System.out);
            }
        }

        @Override
        public void releaseResources() {
        }
    }).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 : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) SocketException(java.net.SocketException) 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) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint)

Example 15 with RequestLine

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

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