Search in sources :

Example 26 with AsyncEntityProducer

use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project httpcomponents-core by apache.

the class BenchmarkWorker method createRequestProducer.

private AsyncRequestProducer createRequestProducer() {
    String method = config.getMethod();
    if (method == null) {
        method = config.isHeadInsteadOfGet() ? Method.HEAD.name() : Method.GET.name();
    }
    final BasicHttpRequest request = new BasicHttpRequest(method, config.getUri());
    final String[] headers = config.getHeaders();
    if (headers != null) {
        for (final String s : headers) {
            final int pos = s.indexOf(':');
            if (pos != -1) {
                request.addHeader(new BasicHeader(s.substring(0, pos).trim(), s.substring(pos + 1)));
            }
        }
    }
    if (!config.isKeepAlive() && !config.isForceHttp2()) {
        request.addHeader(new BasicHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE));
    }
    if (config.isUseAcceptGZip()) {
        request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"));
    }
    if (config.getSoapAction() != null && config.getSoapAction().length() > 0) {
        request.addHeader(new BasicHeader("SOAPAction", config.getSoapAction()));
    }
    final AsyncEntityProducer entityProducer;
    if (config.getPayloadFile() != null) {
        entityProducer = new FileEntityProducer(config.getPayloadFile(), config.getContentType(), config.isUseChunking());
    } else if (config.getPayloadText() != null) {
        entityProducer = new BasicAsyncEntityProducer(config.getPayloadText(), config.getContentType(), config.isUseChunking());
    } else {
        entityProducer = null;
    }
    return new AsyncRequestProducer() {

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

        @Override
        public boolean isRepeatable() {
            return entityProducer == null || entityProducer.isRepeatable();
        }

        @Override
        public int available() {
            return entityProducer != null ? entityProducer.available() : 0;
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            if (entityProducer != null) {
                entityProducer.produce(channel);
            }
        }

        @Override
        public void failed(final Exception cause) {
            if (config.getVerbosity() >= 1) {
                System.out.println("Failed HTTP request: " + cause.getMessage());
            }
        }

        @Override
        public void releaseResources() {
            if (entityProducer != null) {
                entityProducer.releaseResources();
            }
        }
    };
}
Also used : FileEntityProducer(org.apache.hc.core5.http.nio.entity.FileEntityProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 27 with AsyncEntityProducer

use of org.apache.hc.core5.http.nio.AsyncEntityProducer in project mercury by yellow013.

the class AsyncClientInterceptors 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).addRequestInterceptorFirst(new HttpRequestInterceptor() {

        private final AtomicLong count = new AtomicLong(0);

        @Override
        public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
            request.setHeader("request-id", Long.toString(count.incrementAndGet()));
        }
    }).addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new AsyncExecChainHandler() {

        @Override
        public void execute(final HttpRequest request, final AsyncEntityProducer requestEntityProducer, final AsyncExecChain.Scope scope, final AsyncExecChain chain, final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
            final Header idHeader = request.getFirstHeader("request-id");
            if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
                final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
                final ByteBuffer content = ByteBuffer.wrap("bad luck".getBytes(StandardCharsets.US_ASCII));
                final AsyncDataConsumer asyncDataConsumer = asyncExecCallback.handleResponse(response, new BasicEntityDetails(content.remaining(), ContentType.TEXT_PLAIN));
                asyncDataConsumer.consume(content);
                asyncDataConsumer.streamEnd(null);
            } else {
                chain.proceed(request, requestEntityProducer, scope, asyncExecCallback);
            }
        }
    }).build();
    client.start();
    final String requestUri = "http://httpbin.org/get";
    for (int i = 0; i < 20; i++) {
        final SimpleHttpRequest request = SimpleRequestBuilder.get(requestUri).build();
        System.out.println("Executing request " + request);
        final Future<SimpleHttpResponse> future = client.execute(request, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(final SimpleHttpResponse response) {
                System.out.println(request + "->" + new StatusLine(response));
                System.out.println(response.getBody());
            }

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

            @Override
            public void cancelled() {
                System.out.println(request + " cancelled");
            }
        });
        future.get();
    }
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : AsyncExecCallback(org.apache.hc.client5.http.async.AsyncExecCallback) AsyncExecChain(org.apache.hc.client5.http.async.AsyncExecChain) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) AsyncDataConsumer(org.apache.hc.core5.http.nio.AsyncDataConsumer) HttpException(org.apache.hc.core5.http.HttpException) BasicEntityDetails(org.apache.hc.core5.http.impl.BasicEntityDetails) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) IOException(java.io.IOException) AsyncExecChainHandler(org.apache.hc.client5.http.async.AsyncExecChainHandler) ByteBuffer(java.nio.ByteBuffer) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) StatusLine(org.apache.hc.core5.http.message.StatusLine) AtomicLong(java.util.concurrent.atomic.AtomicLong) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) HttpRequestInterceptor(org.apache.hc.core5.http.HttpRequestInterceptor)

Aggregations

AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)27 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)18 Test (org.junit.jupiter.api.Test)16 WritableByteChannelMock (org.apache.hc.core5.http.WritableByteChannelMock)14 BasicDataStreamChannel (org.apache.hc.core5.http.nio.BasicDataStreamChannel)14 IOException (java.io.IOException)8 HttpException (org.apache.hc.core5.http.HttpException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)8 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 Header (org.apache.hc.core5.http.Header)6 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 EntityDetails (org.apache.hc.core5.http.EntityDetails)5 ByteBuffer (java.nio.ByteBuffer)4 Path (java.nio.file.Path)4 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)4 List (java.util.List)3 AsyncDataConsumer (org.apache.hc.core5.http.nio.AsyncDataConsumer)3 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)3 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)3