Does Apache or some other CLIENT JAVA implementation support HTTP/2?

后端 未结 4 1226
野的像风
野的像风 2021-02-14 05:22

I\'m looking for java client that can connect to a HTTP/2 based server.. The server is already supporting HTTP/2 API. I don\'t see the most popular Apache Http client https://hc

4条回答
  •  温柔的废话
    2021-02-14 06:12

    Apache httpclient-5 beta supports http/2 from jdk9 or above

    example :

    public static void main(final String[] args) throws Exception {
        final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
        final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(new H2TlsStrategy(sslContext, NoopHostnameVerifier.INSTANCE)).build();
        final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
        final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, null, ioReactorConfig, connectionManager);
    
        client.start();
        final HttpHost target = new HttpHost("localhost", 8082, "https");
        final Future leaseFuture = client.lease(target, null);
        final AsyncClientEndpoint endpoint = leaseFuture.get(10, TimeUnit.SECONDS);
        try {
            String[] requestUris = new String[] {"/"};
            CountDownLatch latch = new CountDownLatch(requestUris.length);
            for (final String requestUri: requestUris) {
                SimpleHttpRequest request = SimpleHttpRequest.get(target, requestUri);
                endpoint.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), new FutureCallback() {
                        @Override
                        public void completed(final SimpleHttpResponse response) {
                            latch.countDown();
                            System.out.println(requestUri + "->" + response.getCode());
                            System.out.println(response.getBody());
                        }
    
                        @Override
                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(requestUri + "->" + ex);
                            ex.printStackTrace();
                        }
    
                        @Override
                        public void cancelled() {
                            latch.countDown();
                            System.out.println(requestUri + " cancelled");
                        }
    
                    });
            }
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            endpoint.releaseAndReuse();
        }
    
        client.shutdown(ShutdownType.GRACEFUL);
    }
    

    refer : https://hc.apache.org/httpcomponents-client-5.0.x/examples-async.html

提交回复
热议问题