Search in sources :

Example 66 with BasicHttpResponse

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

the class ServerHttp1StreamHandler method consumeHeader.

void consumeHeader(final HttpRequest request, final EntityDetails requestEntityDetails) throws HttpException, IOException {
    if (done.get() || requestState != MessageState.HEADERS) {
        throw new ProtocolException("Unexpected message head");
    }
    receivedRequest = request;
    requestState = requestEntityDetails == null ? MessageState.COMPLETE : MessageState.BODY;
    AsyncServerExchangeHandler handler;
    try {
        handler = exchangeHandlerFactory.create(request, context);
    } catch (final MisdirectedRequestException ex) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_MISDIRECTED_REQUEST, ex.getMessage());
    } catch (final HttpException ex) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    if (handler == null) {
        handler = new ImmediateResponseExchangeHandler(HttpStatus.SC_NOT_FOUND, "Cannot handle request");
    }
    exchangeHandler = handler;
    final ProtocolVersion transportVersion = request.getVersion();
    if (transportVersion != null && transportVersion.greaterEquals(HttpVersion.HTTP_2)) {
        throw new UnsupportedHttpVersionException(transportVersion);
    }
    context.setProtocolVersion(transportVersion != null ? transportVersion : HttpVersion.HTTP_1_1);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    try {
        httpProcessor.process(request, requestEntityDetails, context);
        exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
    } catch (final HttpException ex) {
        if (!responseCommitted.get()) {
            final HttpResponse response = new BasicHttpResponse(ServerSupport.toStatusCode(ex));
            response.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
            final AsyncResponseProducer responseProducer = new BasicResponseProducer(response, ServerSupport.toErrorMessage(ex));
            exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
            exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
        } else {
            throw ex;
        }
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) UnsupportedHttpVersionException(org.apache.hc.core5.http.UnsupportedHttpVersionException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) MisdirectedRequestException(org.apache.hc.core5.http.MisdirectedRequestException) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 67 with BasicHttpResponse

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

BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)60 HttpResponse (org.apache.hc.core5.http.HttpResponse)57 Test (org.junit.jupiter.api.Test)40 HttpRequest (org.apache.hc.core5.http.HttpRequest)15 Header (org.apache.hc.core5.http.Header)14 HttpException (org.apache.hc.core5.http.HttpException)11 IOException (java.io.IOException)10 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)9 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)9 InetSocketAddress (java.net.InetSocketAddress)8 EntityDetails (org.apache.hc.core5.http.EntityDetails)8 ByteBuffer (java.nio.ByteBuffer)7 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)7 Test (org.junit.Test)7 ProtocolException (org.apache.hc.core5.http.ProtocolException)6 AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)6 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)6 Message (org.apache.hc.core5.http.Message)5 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)5 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)5