Search in sources :

Example 1 with HttpRequester

use of org.apache.hc.core5.http.impl.bootstrap.HttpRequester in project httpcomponents-core by apache.

the class ClassicTestClient method execute.

public ClassicHttpResponse execute(final HttpHost targetHost, final ClassicHttpRequest request, final HttpContext context) throws HttpException, IOException {
    final HttpRequester requester = this.requesterRef.get();
    if (requester == null) {
        throw new IllegalStateException("Requester has not been started");
    }
    if (request.getAuthority() == null) {
        request.setAuthority(new URIAuthority(targetHost));
    }
    request.setScheme(targetHost.getSchemeName());
    return requester.execute(targetHost, request, socketConfig.getSoTimeout(), context);
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester)

Example 2 with HttpRequester

use of org.apache.hc.core5.http.impl.bootstrap.HttpRequester in project httpcomponents-core by apache.

the class RequesterBootstrap method create.

public HttpRequester create() {
    final HttpRequestExecutor requestExecutor = new HttpRequestExecutor(HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE, connReuseStrategy != null ? connReuseStrategy : DefaultConnectionReuseStrategy.INSTANCE, streamListener);
    final ManagedConnPool<HttpHost, HttpClientConnection> connPool;
    switch(poolConcurrencyPolicy != null ? poolConcurrencyPolicy : PoolConcurrencyPolicy.STRICT) {
        case LAX:
            connPool = new LaxConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
        case STRICT:
        default:
            connPool = new StrictConnPool<>(defaultMaxPerRoute > 0 ? defaultMaxPerRoute : 20, maxTotal > 0 ? maxTotal : 50, timeToLive, poolReusePolicy, new DefaultDisposalCallback<>(), connPoolListener);
            break;
    }
    return new HttpRequester(requestExecutor, httpProcessor != null ? httpProcessor : HttpProcessors.client(), connPool, socketConfig != null ? socketConfig : SocketConfig.DEFAULT, connectFactory != null ? connectFactory : new DefaultBHttpClientConnectionFactory(Http1Config.DEFAULT, CharCodingConfig.DEFAULT), sslSocketFactory, sslSetupHandler != null ? sslSetupHandler : new DefaultTlsSetupHandler(), sslSessionVerifier, DefaultAddressResolver.INSTANCE);
}
Also used : HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) DefaultDisposalCallback(org.apache.hc.core5.pool.DefaultDisposalCallback) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientConnection(org.apache.hc.core5.http.io.HttpClientConnection) DefaultBHttpClientConnectionFactory(org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnectionFactory) DefaultTlsSetupHandler(org.apache.hc.core5.http.io.ssl.DefaultTlsSetupHandler)

Example 3 with HttpRequester

use of org.apache.hc.core5.http.impl.bootstrap.HttpRequester in project httpcomponents-core by apache.

the class ClassicGetExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final HttpRequester httpRequester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).setSocketConfig(SocketConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).create();
    final HttpCoreContext coreContext = HttpCoreContext.create();
    final HttpHost target = new HttpHost("httpbin.org");
    final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    for (int i = 0; i < requestUris.length; i++) {
        final String requestUri = requestUris[i];
        final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
        try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
            System.out.println(requestUri + "->" + response.getCode());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
        }
    }
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester)

Example 4 with HttpRequester

use of org.apache.hc.core5.http.impl.bootstrap.HttpRequester in project httpcomponents-core by apache.

the class ClassicPostExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final HttpRequester httpRequester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).setSocketConfig(SocketConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).create();
    final HttpCoreContext coreContext = HttpCoreContext.create();
    final HttpHost target = new HttpHost("httpbin.org");
    final HttpEntity[] requestBodies = { HttpEntities.create("This is the first test request", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the second test request".getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM), HttpEntities.create(outStream -> outStream.write(("This is the third test request " + "(streaming)").getBytes(StandardCharsets.UTF_8)), ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the fourth test request " + "(streaming with trailers)", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8), new BasicHeader("trailer1", "And goodbye")) };
    final String requestUri = "/post";
    for (int i = 0; i < requestBodies.length; i++) {
        final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
        request.setEntity(requestBodies[i]);
        try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
            System.out.println(requestUri + "->" + response.getCode());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
        }
    }
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester) ClassicRequestBuilder(org.apache.hc.core5.http.io.support.ClassicRequestBuilder) RequesterBootstrap(org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) RequestLine(org.apache.hc.core5.http.message.RequestLine) Timeout(org.apache.hc.core5.util.Timeout) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) HttpRequest(org.apache.hc.core5.http.HttpRequest) ContentType(org.apache.hc.core5.http.ContentType) HttpConnection(org.apache.hc.core5.http.HttpConnection) HttpEntities(org.apache.hc.core5.http.io.entity.HttpEntities) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) EntityUtils(org.apache.hc.core5.http.io.entity.EntityUtils) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester) BasicHeader(org.apache.hc.core5.http.message.BasicHeader)

Example 5 with HttpRequester

use of org.apache.hc.core5.http.impl.bootstrap.HttpRequester in project httpcomponents-core by apache.

the class ClassicReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port]");
        System.exit(1);
    }
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    System.out.println("Reverse proxy to " + targetHost);
    final HttpRequester requester = RequesterBootstrap.bootstrap().setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[proxy->origin] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[proxy<-origin] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setConnPoolListener(new ConnPoolListener<HttpHost>() {

        @Override
        public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection leased ").append(route);
            System.out.println(buf);
        }

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] ").append(Thread.currentThread()).append(" connection released ").append(route);
            final PoolStats totals = connPoolStats.getTotalStats();
            buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
            buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
            buf.append(" of ").append(totals.getMax());
            System.out.println(buf);
        }
    }).create();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println("[client->proxy] " + Thread.currentThread() + " " + request.getMethod() + " " + request.getRequestUri());
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " status " + response.getCode());
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            System.out.println("[client<-proxy] " + Thread.currentThread() + " exchange completed; " + "connection " + (keepAlive ? "kept alive" : "cannot be kept alive"));
        }
    }).setExceptionListener(new ExceptionListener() {

        @Override
        public void onError(final Exception ex) {
            if (ex instanceof SocketException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }

        @Override
        public void onError(final HttpConnection connection, final Exception ex) {
            if (ex instanceof SocketTimeoutException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " time out");
            } else if (ex instanceof SocketException || ex instanceof ConnectionClosedException) {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
            } else {
                System.out.println("[client->proxy] " + Thread.currentThread() + " " + ex.getMessage());
                ex.printStackTrace(System.out);
            }
        }
    }).register("*", new ProxyHandler(targetHost, requester)).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) SocketTimeoutException(java.net.SocketTimeoutException) HttpHost(org.apache.hc.core5.http.HttpHost) ConnPoolListener(org.apache.hc.core5.pool.ConnPoolListener) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) ExceptionListener(org.apache.hc.core5.http.ExceptionListener) HttpRequester(org.apache.hc.core5.http.impl.bootstrap.HttpRequester)

Aggregations

HttpHost (org.apache.hc.core5.http.HttpHost)5 HttpRequester (org.apache.hc.core5.http.impl.bootstrap.HttpRequester)5 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)3 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)3 HttpConnection (org.apache.hc.core5.http.HttpConnection)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 HttpResponse (org.apache.hc.core5.http.HttpResponse)3 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)3 HttpRequestExecutor (org.apache.hc.core5.http.impl.io.HttpRequestExecutor)2 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)2 RequestLine (org.apache.hc.core5.http.message.RequestLine)2 StatusLine (org.apache.hc.core5.http.message.StatusLine)2 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)2 IOException (java.io.IOException)1 SocketException (java.net.SocketException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 TimeUnit (java.util.concurrent.TimeUnit)1 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)1 ContentType (org.apache.hc.core5.http.ContentType)1