Search in sources :

Example 1 with HttpResponseInformationCallback

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

the class HttpRequester method execute.

public ClassicHttpResponse execute(final HttpClientConnection connection, final ClassicHttpRequest request, final HttpResponseInformationCallback informationCallback, final HttpContext context) throws HttpException, IOException {
    Args.notNull(connection, "HTTP connection");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    if (!connection.isOpen()) {
        throw new ConnectionClosedException();
    }
    requestExecutor.preProcess(request, httpProcessor, context);
    final ClassicHttpResponse response = requestExecutor.execute(request, connection, informationCallback, context);
    requestExecutor.postProcess(response, httpProcessor, context);
    return response;
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException)

Example 2 with HttpResponseInformationCallback

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

the class TestHttpRequestExecutor method testExecutionSkipIntermediateResponses.

@Test
public void testExecutionSkipIntermediateResponses() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.GET, "/");
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(100, "Continue"), new BasicClassicHttpResponse(110, "Huh?"), new BasicClassicHttpResponse(111, "Huh?"), new BasicClassicHttpResponse(200, "OK"));
    final HttpResponseInformationCallback callback = Mockito.mock(HttpResponseInformationCallback.class);
    final ClassicHttpResponse response = executor.execute(request, conn, callback, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn).flush();
    Mockito.verify(conn, Mockito.times(4)).receiveResponseHeader();
    Mockito.verify(conn, Mockito.times(1)).receiveResponseEntity(response);
    final ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);
    Mockito.verify(callback, Mockito.times(2)).execute(responseCaptor.capture(), ArgumentMatchers.eq(conn), ArgumentMatchers.eq(context));
    final List<HttpResponse> infos = responseCaptor.getAllValues();
    Assertions.assertNotNull(infos);
    Assertions.assertEquals(2, infos.size());
    final HttpResponse info1 = infos.get(0);
    Assertions.assertNotNull(info1);
    Assertions.assertEquals(110, info1.getCode());
    final HttpResponse info2 = infos.get(1);
    Assertions.assertNotNull(info2);
    Assertions.assertEquals(111, info2.getCode());
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
    Assertions.assertSame(request, context.getRequest());
    Assertions.assertSame(response, context.getResponse());
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponseInformationCallback(org.apache.hc.core5.http.io.HttpResponseInformationCallback) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 3 with HttpResponseInformationCallback

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

the class HttpRequester method execute.

public ClassicHttpResponse execute(final HttpHost targetHost, final ClassicHttpRequest request, final HttpResponseInformationCallback informationCallback, final Timeout connectTimeout, final HttpContext context) throws HttpException, IOException {
    Args.notNull(targetHost, "HTTP host");
    Args.notNull(request, "HTTP request");
    final Future<PoolEntry<HttpHost, HttpClientConnection>> leaseFuture = connPool.lease(targetHost, null, connectTimeout, null);
    final PoolEntry<HttpHost, HttpClientConnection> poolEntry;
    final Timeout timeout = Timeout.defaultsToDisabled(connectTimeout);
    try {
        poolEntry = leaseFuture.get(timeout.getDuration(), timeout.getTimeUnit());
    } catch (final InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new InterruptedIOException(ex.getMessage());
    } catch (final ExecutionException ex) {
        throw new HttpException("Unexpected failure leasing connection", ex);
    } catch (final TimeoutException ex) {
        throw new ConnectionRequestTimeoutException("Connection request timeout");
    }
    final PoolEntryHolder connectionHolder = new PoolEntryHolder(poolEntry);
    try {
        HttpClientConnection connection = poolEntry.getConnection();
        if (connection == null) {
            final Socket socket = createSocket(targetHost);
            connection = connectFactory.createConnection(socket);
            poolEntry.assignConnection(connection);
        }
        if (request.getAuthority() == null) {
            request.setAuthority(new URIAuthority(targetHost.getHostName(), targetHost.getPort()));
        }
        final ClassicHttpResponse response = execute(connection, request, informationCallback, context);
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new HttpEntityWrapper(entity) {

                private void releaseConnection() throws IOException {
                    try {
                        final HttpClientConnection localConn = connectionHolder.getConnection();
                        if (localConn != null) {
                            if (requestExecutor.keepAlive(request, response, localConn, context)) {
                                if (super.isStreaming()) {
                                    Closer.close(super.getContent());
                                }
                                connectionHolder.releaseConnection();
                            }
                        }
                    } finally {
                        connectionHolder.discardConnection();
                    }
                }

                private void abortConnection() {
                    connectionHolder.discardConnection();
                }

                @Override
                public boolean isStreaming() {
                    return true;
                }

                @Override
                public InputStream getContent() throws IOException {
                    return new EofSensorInputStream(super.getContent(), new EofSensorWatcher() {

                        @Override
                        public boolean eofDetected(final InputStream wrapped) throws IOException {
                            releaseConnection();
                            return false;
                        }

                        @Override
                        public boolean streamClosed(final InputStream wrapped) throws IOException {
                            releaseConnection();
                            return false;
                        }

                        @Override
                        public boolean streamAbort(final InputStream wrapped) throws IOException {
                            abortConnection();
                            return false;
                        }
                    });
                }

                @Override
                public void writeTo(final OutputStream outStream) throws IOException {
                    try {
                        if (outStream != null) {
                            super.writeTo(outStream);
                        }
                        close();
                    } catch (final IOException | RuntimeException ex) {
                        abortConnection();
                    }
                }

                @Override
                public void close() throws IOException {
                    releaseConnection();
                }
            });
        } else {
            final HttpClientConnection localConn = connectionHolder.getConnection();
            if (!requestExecutor.keepAlive(request, response, localConn, context)) {
                localConn.close();
            }
            connectionHolder.releaseConnection();
        }
        return response;
    } catch (final HttpException | IOException | RuntimeException ex) {
        connectionHolder.discardConnection();
        throw ex;
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) OutputStream(java.io.OutputStream) EofSensorWatcher(org.apache.hc.core5.http.io.EofSensorWatcher) HttpEntityWrapper(org.apache.hc.core5.http.io.entity.HttpEntityWrapper) EofSensorInputStream(org.apache.hc.core5.http.io.EofSensorInputStream) HttpHost(org.apache.hc.core5.http.HttpHost) HttpException(org.apache.hc.core5.http.HttpException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ConnectionRequestTimeoutException(org.apache.hc.core5.http.ConnectionRequestTimeoutException) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) ConnectionRequestTimeoutException(org.apache.hc.core5.http.ConnectionRequestTimeoutException) Timeout(org.apache.hc.core5.util.Timeout) EofSensorInputStream(org.apache.hc.core5.http.io.EofSensorInputStream) InputStream(java.io.InputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) PoolEntry(org.apache.hc.core5.pool.PoolEntry) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 4 with HttpResponseInformationCallback

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

the class TestHttpRequestExecutor method testExecutionEntityEnclosingRequestWithExpectContinueMultiple1xxResponses.

@Test
public void testExecutionEntityEnclosingRequestWithExpectContinueMultiple1xxResponses() throws Exception {
    final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
    final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class);
    final HttpRequestExecutor executor = new HttpRequestExecutor();
    final HttpCoreContext context = HttpCoreContext.create();
    final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, "/");
    request.addHeader(HttpHeaders.EXPECT, HeaderElements.CONTINUE);
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    request.setEntity(entity);
    executor.preProcess(request, httprocessor, context);
    Mockito.verify(httprocessor).process(request, request.getEntity(), context);
    Mockito.when(conn.receiveResponseHeader()).thenReturn(new BasicClassicHttpResponse(110, "Huh?"), new BasicClassicHttpResponse(100, "Continue"), new BasicClassicHttpResponse(111, "Huh?"), new BasicClassicHttpResponse(200, "OK"));
    Mockito.when(conn.isDataAvailable(ArgumentMatchers.any(Timeout.class))).thenReturn(Boolean.TRUE);
    final HttpResponseInformationCallback callback = Mockito.mock(HttpResponseInformationCallback.class);
    final ClassicHttpResponse response = executor.execute(request, conn, callback, context);
    Mockito.verify(conn).sendRequestHeader(request);
    Mockito.verify(conn).sendRequestEntity(request);
    Mockito.verify(conn, Mockito.times(2)).flush();
    Mockito.verify(conn, Mockito.times(2)).isDataAvailable(Timeout.ofMilliseconds(3000));
    Mockito.verify(conn, Mockito.times(4)).receiveResponseHeader();
    Mockito.verify(conn).receiveResponseEntity(response);
    final ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);
    Mockito.verify(callback, Mockito.times(2)).execute(responseCaptor.capture(), ArgumentMatchers.eq(conn), ArgumentMatchers.eq(context));
    final List<HttpResponse> infos = responseCaptor.getAllValues();
    Assertions.assertNotNull(infos);
    Assertions.assertEquals(2, infos.size());
    final HttpResponse info1 = infos.get(0);
    Assertions.assertNotNull(info1);
    Assertions.assertEquals(110, info1.getCode());
    final HttpResponse info2 = infos.get(1);
    Assertions.assertNotNull(info2);
    Assertions.assertEquals(111, info2.getCode());
    executor.postProcess(response, httprocessor, context);
    Mockito.verify(httprocessor).process(response, response.getEntity(), context);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) Timeout(org.apache.hc.core5.util.Timeout) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpResponseInformationCallback(org.apache.hc.core5.http.io.HttpResponseInformationCallback) 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) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 5 with HttpResponseInformationCallback

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

the class HttpRequestExecutor method execute.

/**
 * Sends the request and obtain a response.
 *
 * @param request   the request to execute.
 * @param conn      the connection over which to execute the request.
 * @param informationCallback   callback to execute upon receipt of information status (1xx).
 *                              May be null.
 * @param context the context
 * @return  the response to the request.
 *
 * @throws IOException in case of an I/O error.
 * @throws HttpException in case of HTTP protocol violation or a processing
 *   problem.
 */
public ClassicHttpResponse execute(final ClassicHttpRequest request, final HttpClientConnection conn, final HttpResponseInformationCallback informationCallback, final HttpContext context) throws IOException, HttpException {
    Args.notNull(request, "HTTP request");
    Args.notNull(conn, "Client connection");
    Args.notNull(context, "HTTP context");
    try {
        context.setAttribute(HttpCoreContext.SSL_SESSION, conn.getSSLSession());
        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, conn.getEndpointDetails());
        conn.sendRequestHeader(request);
        if (streamListener != null) {
            streamListener.onRequestHead(conn, request);
        }
        boolean expectContinue = false;
        final HttpEntity entity = request.getEntity();
        if (entity != null) {
            final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
            expectContinue = expect != null && HeaderElements.CONTINUE.equalsIgnoreCase(expect.getValue());
            if (!expectContinue) {
                conn.sendRequestEntity(request);
            }
        }
        conn.flush();
        ClassicHttpResponse response = null;
        while (response == null) {
            if (expectContinue) {
                if (conn.isDataAvailable(this.waitForContinue)) {
                    response = conn.receiveResponseHeader();
                    if (streamListener != null) {
                        streamListener.onResponseHead(conn, response);
                    }
                    final int status = response.getCode();
                    if (status == HttpStatus.SC_CONTINUE) {
                        // discard 100-continue
                        response = null;
                        conn.sendRequestEntity(request);
                    } else if (status < HttpStatus.SC_SUCCESS) {
                        if (informationCallback != null) {
                            informationCallback.execute(response, conn, context);
                        }
                        response = null;
                        continue;
                    } else if (status >= HttpStatus.SC_CLIENT_ERROR) {
                        conn.terminateRequest(request);
                    } else {
                        conn.sendRequestEntity(request);
                    }
                } else {
                    conn.sendRequestEntity(request);
                }
                conn.flush();
                expectContinue = false;
            } else {
                response = conn.receiveResponseHeader();
                if (streamListener != null) {
                    streamListener.onResponseHead(conn, response);
                }
                final int status = response.getCode();
                if (status < HttpStatus.SC_INFORMATIONAL) {
                    throw new ProtocolException("Invalid response: " + new StatusLine(response));
                }
                if (status < HttpStatus.SC_SUCCESS) {
                    if (informationCallback != null && status != HttpStatus.SC_CONTINUE) {
                        informationCallback.execute(response, conn, context);
                    }
                    response = null;
                }
            }
        }
        if (MessageSupport.canResponseHaveBody(request.getMethod(), response)) {
            conn.receiveResponseEntity(response);
        }
        return response;
    } catch (final HttpException | IOException | RuntimeException ex) {
        Closer.closeQuietly(conn);
        throw ex;
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) StatusLine(org.apache.hc.core5.http.message.StatusLine) ProtocolException(org.apache.hc.core5.http.ProtocolException) HttpEntity(org.apache.hc.core5.http.HttpEntity) Header(org.apache.hc.core5.http.Header) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException)

Aggregations

ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)5 HttpEntity (org.apache.hc.core5.http.HttpEntity)3 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)3 IOException (java.io.IOException)2 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)2 HttpException (org.apache.hc.core5.http.HttpException)2 HttpResponse (org.apache.hc.core5.http.HttpResponse)2 HttpResponseInformationCallback (org.apache.hc.core5.http.io.HttpResponseInformationCallback)2 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)2 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)2 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)2 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)2 Timeout (org.apache.hc.core5.util.Timeout)2 Test (org.junit.jupiter.api.Test)2 InputStream (java.io.InputStream)1 InterruptedIOException (java.io.InterruptedIOException)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1