Search in sources :

Example 11 with ProtocolException

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

the class RequestContent method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    final String method = request.getMethod();
    if (Method.TRACE.isSame(method) && entity != null) {
        throw new ProtocolException("TRACE request may not enclose an entity");
    }
    if (this.overwrite) {
        request.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
        request.removeHeaders(HttpHeaders.CONTENT_LENGTH);
    } else {
        if (request.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
            throw new ProtocolException("Transfer-encoding header already present");
        }
        if (request.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
            throw new ProtocolException("Content-Length header already present");
        }
    }
    if (entity != null) {
        final ProtocolVersion ver = context.getProtocolVersion();
        // Must specify a transfer encoding or a content length
        if (entity.isChunked() || entity.getContentLength() < 0) {
            if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
                throw new ProtocolException("Chunked transfer encoding not allowed for " + ver);
            }
            request.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
            MessageSupport.addTrailerHeader(request, entity);
        } else {
            request.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
        }
        MessageSupport.addContentTypeHeader(request, entity);
        MessageSupport.addContentEncodingHeader(request, entity);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 12 with ProtocolException

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

the class TestHttpService method testProtocolException.

@Test
public void testProtocolException() throws Exception {
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest("whatever", "/");
    Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
    Mockito.when(responseFactory.newHttpResponse(200)).thenReturn(response);
    Mockito.when(handlerResolver.resolve(request, context)).thenReturn(requestHandler);
    Mockito.doThrow(new ProtocolException("oh, this world is wrong")).when(requestHandler).handle(request, response, context);
    httpservice.handleRequest(conn, context);
    final ArgumentCaptor<ClassicHttpResponse> responseCaptor = ArgumentCaptor.forClass(ClassicHttpResponse.class);
    Mockito.verify(conn).sendResponseHeader(responseCaptor.capture());
    final ClassicHttpResponse error = responseCaptor.getValue();
    Assertions.assertNotNull(error);
    Assertions.assertSame(request, context.getRequest());
    Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, error.getCode());
    Mockito.verify(httprocessor).process(error, error.getEntity(), context);
    Mockito.verify(conn).sendResponseHeader(error);
    Mockito.verify(conn).sendResponseEntity(error);
    Mockito.verify(conn).close();
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) Test(org.junit.jupiter.api.Test)

Example 13 with ProtocolException

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

the class ServerHttp1StreamHandler method terminateExchange.

void terminateExchange(final HttpException ex) throws HttpException, IOException {
    if (done.get() || requestState != MessageState.HEADERS) {
        throw new ProtocolException("Unexpected message head");
    }
    receivedRequest = null;
    requestState = MessageState.COMPLETE;
    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(null, null, responseChannel, context);
}
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) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer)

Example 14 with ProtocolException

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

the class HeaderGroup method getHeader.

/**
 * Gets single first header with the given name.
 *
 * <p>Header name comparison is case insensitive.
 *
 * @param name the name of the header to get
 * @return the first header or {@code null}
 * @throws ProtocolException in case multiple headers with the given name are found.
 */
@Override
public Header getHeader(final String name) throws ProtocolException {
    int count = 0;
    Header singleHeader = null;
    for (int i = 0; i < this.headers.size(); i++) {
        final Header header = this.headers.get(i);
        if (header.getName().equalsIgnoreCase(name)) {
            singleHeader = header;
            count++;
        }
    }
    if (count > 1) {
        throw new ProtocolException("multiple '%s' headers found", name);
    }
    return singleHeader;
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) Header(org.apache.hc.core5.http.Header)

Example 15 with ProtocolException

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

the class HttpAsyncRequester method execute.

public void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext executeContext) {
    Args.notNull(exchangeHandler, "Exchange handler");
    Args.notNull(timeout, "Timeout");
    Args.notNull(executeContext, "Context");
    try {
        exchangeHandler.produceRequest((request, entityDetails, requestContext) -> {
            final String scheme = request.getScheme();
            final URIAuthority authority = request.getAuthority();
            if (authority == null) {
                throw new ProtocolException("Request authority not specified");
            }
            final HttpHost target = new HttpHost(scheme, authority);
            connect(target, timeout, null, new FutureCallback<AsyncClientEndpoint>() {

                @Override
                public void completed(final AsyncClientEndpoint endpoint) {
                    endpoint.execute(new AsyncClientExchangeHandler() {

                        @Override
                        public void releaseResources() {
                            endpoint.releaseAndDiscard();
                            exchangeHandler.releaseResources();
                        }

                        @Override
                        public void failed(final Exception cause) {
                            endpoint.releaseAndDiscard();
                            exchangeHandler.failed(cause);
                        }

                        @Override
                        public void cancel() {
                            endpoint.releaseAndDiscard();
                            exchangeHandler.cancel();
                        }

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

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

                        @Override
                        public void produce(final DataStreamChannel channel) throws IOException {
                            exchangeHandler.produce(channel);
                        }

                        @Override
                        public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
                            exchangeHandler.consumeInformation(response, httpContext);
                        }

                        @Override
                        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                            if (entityDetails == null) {
                                endpoint.releaseAndReuse();
                            }
                            exchangeHandler.consumeResponse(response, entityDetails, httpContext);
                        }

                        @Override
                        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
                            exchangeHandler.updateCapacity(capacityChannel);
                        }

                        @Override
                        public void consume(final ByteBuffer src) throws IOException {
                            exchangeHandler.consume(src);
                        }

                        @Override
                        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                            endpoint.releaseAndReuse();
                            exchangeHandler.streamEnd(trailers);
                        }
                    }, pushHandlerFactory, executeContext);
                }

                @Override
                public void failed(final Exception ex) {
                    exchangeHandler.failed(ex);
                }

                @Override
                public void cancelled() {
                    exchangeHandler.cancel();
                }
            });
        }, executeContext);
    } catch (final IOException | HttpException ex) {
        exchangeHandler.failed(ex);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Aggregations

ProtocolException (org.apache.hc.core5.http.ProtocolException)28 HttpResponse (org.apache.hc.core5.http.HttpResponse)10 Header (org.apache.hc.core5.http.Header)9 EntityDetails (org.apache.hc.core5.http.EntityDetails)8 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)8 URISyntaxException (java.net.URISyntaxException)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpRequest (org.apache.hc.core5.http.HttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 IOException (java.io.IOException)5 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)5 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)5 ByteBuffer (java.nio.ByteBuffer)4 ArrayList (java.util.ArrayList)4 URIAuthority (org.apache.hc.core5.net.URIAuthority)4 InetSocketAddress (java.net.InetSocketAddress)3 URI (java.net.URI)3 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 Message (org.apache.hc.core5.http.Message)3