Search in sources :

Example 31 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class ClientH2UpgradeHandler method upgrade.

@Override
public void upgrade(final ProtocolIOSession ioSession, final FutureCallback<ProtocolIOSession> callback) {
    final HttpConnectionEventHandler protocolNegotiator = new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, true, callback);
    ioSession.upgrade(protocolNegotiator);
    try {
        protocolNegotiator.connected(ioSession);
    } catch (final IOException ex) {
        protocolNegotiator.exception(ioSession, ex);
    }
}
Also used : HttpConnectionEventHandler(org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler) IOException(java.io.IOException)

Example 32 with Callback

use of org.apache.hc.core5.function.Callback in project httpcomponents-core by apache.

the class H2ConnPool method validateSession.

@Override
protected void validateSession(final IOSession ioSession, final Callback<Boolean> callback) {
    if (ioSession.isOpen()) {
        final TimeValue timeValue = validateAfterInactivity;
        if (TimeValue.isNonNegative(timeValue)) {
            final long lastAccessTime = Math.min(ioSession.getLastReadTime(), ioSession.getLastWriteTime());
            final long deadline = lastAccessTime + timeValue.toMilliseconds();
            if (deadline <= System.currentTimeMillis()) {
                final Timeout socketTimeoutMillis = ioSession.getSocketTimeout();
                ioSession.enqueue(new PingCommand(new BasicPingHandler(result -> {
                    ioSession.setSocketTimeout(socketTimeoutMillis);
                    callback.execute(result);
                })), Command.Priority.NORMAL);
                return;
            }
        }
        callback.execute(true);
    } else {
        callback.execute(false);
    }
}
Also used : Timeout(org.apache.hc.core5.util.Timeout) BasicPingHandler(org.apache.hc.core5.http2.nio.support.BasicPingHandler) TimeValue(org.apache.hc.core5.util.TimeValue) PingCommand(org.apache.hc.core5.http2.nio.command.PingCommand)

Example 33 with Callback

use of org.apache.hc.core5.function.Callback 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)

Example 34 with Callback

use of org.apache.hc.core5.function.Callback in project mercury by yellow013.

the class ClientWithRequestFuture method main.

public static void main(final String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    final CloseableHttpClient httpclient = HttpClientBuilder.create().setConnectionManager(cm).build();
    final ExecutorService execService = Executors.newFixedThreadPool(5);
    try (final FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService)) {
        // Because things are asynchronous, you must provide a HttpClientResponseHandler
        final HttpClientResponseHandler<Boolean> handler = new HttpClientResponseHandler<Boolean>() {

            @Override
            public Boolean handleResponse(final ClassicHttpResponse response) throws IOException {
                // simply return true if the status was OK
                return response.getCode() == HttpStatus.SC_OK;
            }
        };
        // Simple request ...
        final HttpGet request1 = new HttpGet("http://httpbin.org/get");
        final FutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler);
        final Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);
        // Cancel a request
        try {
            final HttpGet request2 = new HttpGet("http://httpbin.org/get");
            final FutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            final Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (final CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }
        // Request with a timeout
        final HttpGet request3 = new HttpGet("http://httpbin.org/get");
        final FutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler);
        final Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);
        final FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {

            @Override
            public void completed(final Boolean result) {
                System.out.println("completed with " + result);
            }

            @Override
            public void failed(final Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        };
        // Simple request with a callback
        final HttpGet request4 = new HttpGet("http://httpbin.org/get");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        final FutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback);
        final Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CancellationException(java.util.concurrent.CancellationException) IOException(java.io.IOException) HttpClientResponseHandler(org.apache.hc.core5.http.io.HttpClientResponseHandler) FutureRequestExecutionService(org.apache.hc.client5.http.impl.classic.FutureRequestExecutionService) CancellationException(java.util.concurrent.CancellationException) ExecutorService(java.util.concurrent.ExecutorService) HttpClientConnectionManager(org.apache.hc.client5.http.io.HttpClientConnectionManager) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Aggregations

Test (org.junit.jupiter.api.Test)10 IOException (java.io.IOException)6 FutureCallback (org.apache.hc.core5.concurrent.FutureCallback)6 CancellationException (java.util.concurrent.CancellationException)5 TimeoutException (java.util.concurrent.TimeoutException)5 HttpResponse (org.apache.hc.core5.http.HttpResponse)5 ExecutionException (java.util.concurrent.ExecutionException)4 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)4 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)4 TimeoutValueException (org.apache.hc.core5.util.TimeoutValueException)4 Stopwatch (com.google.common.base.Stopwatch)3 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)3 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)3 ContentType (org.apache.hc.core5.http.ContentType)3 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)3 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)2 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2