Search in sources :

Example 21 with Args

use of org.apache.hc.core5.util.Args in project eomcs-java by eomcs.

the class Exam0130 method main.

public static void main(String[] args) throws Exception {
    // 
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet("https://www.daum.net");
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            System.out.println(response.getCode() + " " + response.getReasonPhrase());
            HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity));
        }
    }
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 22 with Args

use of org.apache.hc.core5.util.Args in project mercury by yellow013.

the class AsyncClientConnectionEviction 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).evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(10)).build();
    client.start();
    final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(new HttpHost("httpbin.org")).setPath("/").build();
    System.out.println("Executing request " + request);
    final Future<SimpleHttpResponse> future1 = client.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), 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");
        }
    });
    future1.get();
    Thread.sleep(TimeUnit.SECONDS.toMillis(30));
    // Previous connection should get evicted from the pool by now
    final Future<SimpleHttpResponse> future2 = 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");
        }
    });
    future2.get();
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse)

Example 23 with Args

use of org.apache.hc.core5.util.Args in project mercury by yellow013.

the class AsyncClientCustomSSL method main.

public static void main(final String[] args) throws Exception {
    // Trust standard CA and those trusted by our custom strategy
    final SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            final X509Certificate cert = chain[0];
            return "CN=httpbin.org".equalsIgnoreCase(cert.getSubjectDN().getName());
        }
    }).build();
    final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create().setSslContext(sslcontext).build();
    final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(tlsStrategy).build();
    try (final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build()) {
        client.start();
        final HttpHost target = new HttpHost("https", "httpbin.org");
        final HttpClientContext clientContext = HttpClientContext.create();
        final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath("/").build();
        System.out.println("Executing request " + request);
        final Future<SimpleHttpResponse> future = client.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), clientContext, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(final SimpleHttpResponse response) {
                System.out.println(request + "->" + new StatusLine(response));
                final SSLSession sslSession = clientContext.getSSLSession();
                if (sslSession != null) {
                    System.out.println("SSL protocol " + sslSession.getProtocol());
                    System.out.println("SSL cipher suite " + sslSession.getCipherSuite());
                }
                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 : TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) TrustStrategy(org.apache.hc.core5.ssl.TrustStrategy) SSLSession(javax.net.ssl.SSLSession) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) CertificateException(java.security.cert.CertificateException) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) PoolingAsyncClientConnectionManager(org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager)

Example 24 with Args

use of org.apache.hc.core5.util.Args in project mercury by yellow013.

the class AsyncClientFullDuplexExchange method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.NEGOTIATE, H2Config.DEFAULT, Http1Config.DEFAULT, ioReactorConfig);
    client.start();
    final BasicHttpRequest request = BasicRequestBuilder.post("http://httpbin.org/post").build();
    final BasicRequestProducer requestProducer = new BasicRequestProducer(request, new BasicAsyncEntityProducer("stuff", ContentType.TEXT_PLAIN));
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    System.out.println("Executing request " + request);
    final CountDownLatch latch = new CountDownLatch(1);
    client.execute(new AsyncClientExchangeHandler() {

        @Override
        public void releaseResources() {
            requestProducer.releaseResources();
            responseConsumer.releaseResources();
            latch.countDown();
        }

        @Override
        public void cancel() {
            System.out.println(request + " cancelled");
        }

        @Override
        public void failed(final Exception cause) {
            System.out.println(request + "->" + cause);
        }

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

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

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

        @Override
        public void consumeInformation(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
            responseConsumer.consumeResponse(response, entityDetails, context, null);
        }

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

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

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            responseConsumer.streamEnd(trailers);
        }
    });
    latch.await(1, TimeUnit.MINUTES);
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) MinimalHttpAsyncClient(org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 25 with Args

use of org.apache.hc.core5.util.Args in project mercury by yellow013.

the class AsyncClientH2Multiplexing method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, null, ioReactorConfig);
    client.start();
    final HttpHost target = new HttpHost("https", "nghttp2.org");
    final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
    final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
    try {
        final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
        final CountDownLatch latch = new CountDownLatch(requestUris.length);
        for (final String requestUri : requestUris) {
            final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
            System.out.println("Executing request " + request);
            endpoint.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() {

                @Override
                public void completed(final SimpleHttpResponse response) {
                    latch.countDown();
                    System.out.println(request + "->" + new StatusLine(response));
                    System.out.println(response.getBody());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request + " cancelled");
                }
            });
        }
        latch.await();
    } finally {
        endpoint.releaseAndReuse();
    }
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : MinimalHttpAsyncClient(org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) CountDownLatch(java.util.concurrent.CountDownLatch) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) HttpHost(org.apache.hc.core5.http.HttpHost)

Aggregations

HttpHost (org.apache.hc.core5.http.HttpHost)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)25 HttpResponse (org.apache.hc.core5.http.HttpResponse)24 StatusLine (org.apache.hc.core5.http.message.StatusLine)22 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)22 IOException (java.io.IOException)21 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)19 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)19 HttpConnection (org.apache.hc.core5.http.HttpConnection)19 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)17 Header (org.apache.hc.core5.http.Header)17 HttpException (org.apache.hc.core5.http.HttpException)16 CountDownLatch (java.util.concurrent.CountDownLatch)13 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)13 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)12 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)12 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)12 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)12 EntityDetails (org.apache.hc.core5.http.EntityDetails)11 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)11