Does Apache or some other CLIENT JAVA implementation support HTTP/2?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
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.apache.org/ still supporting HTTP/2.
Does Apache have some implementation for Java client already that supports Http/2?
If not, Is there some java client that supports connecting to HTTP/2 preferably on Java 7?
java apache http httpclient http2
add a comment |
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.apache.org/ still supporting HTTP/2.
Does Apache have some implementation for Java client already that supports Http/2?
If not, Is there some java client that supports connecting to HTTP/2 preferably on Java 7?
java apache http httpclient http2
add a comment |
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.apache.org/ still supporting HTTP/2.
Does Apache have some implementation for Java client already that supports Http/2?
If not, Is there some java client that supports connecting to HTTP/2 preferably on Java 7?
java apache http httpclient http2
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.apache.org/ still supporting HTTP/2.
Does Apache have some implementation for Java client already that supports Http/2?
If not, Is there some java client that supports connecting to HTTP/2 preferably on Java 7?
java apache http httpclient http2
java apache http httpclient http2
edited Jan 16 '16 at 4:43
marcospereira
10.4k33544
10.4k33544
asked Jan 16 '16 at 4:10
Neeraj KrishnaNeeraj Krishna
9851117
9851117
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
Jetty's provides two HTTP/2 Java client APIs. Both require Java 8 and the mandatory use of the ALPN, as explained here.
Low level APIs
These APIs are based on HTTP2Client, it's based on the HTTP/2 concepts of session and streams and uses listeners to be notified of the HTTP/2 frames that arrive from the server.
// Setup and start the HTTP2Client.
HTTP2Client client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
client.addBean(sslContextFactory);
client.start();
// Connect to the remote host to obtains a Session.
FuturePromise<Session> sessionPromise = new FuturePromise<>();
client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);
Session session = sessionPromise.get(5, TimeUnit.SECONDS);
// Use the session to make requests.
HttpFields requestFields = new HttpFields();
requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://webtide.com/"), HttpVersion.HTTP_2, requestFields);
HeadersFrame headersFrame = new HeadersFrame(metaData, null, true);
session.newStream(headersFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Response headers.
System.err.println(frame);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Response content.
System.err.println(frame);
callback.succeeded();
}
});
High Level APIs
Jetty's HttpClient
provides a way to use different transports, one of which is the HTTP/2 transport. Applications will use the higher level HTTP APIs, but underneath Jetty will use HTTP/2 to transport the HTTP semantic.
In this way, applications can use the high level APIs provided by HttpClient
transparently, and factor out what transport to use in configuration or startup code.
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
add a comment |
There is OkHttp: An HTTP & HTTP/2 client for Android and Java applications.
add a comment |
Jetty has support for HTTP2 starting from version 9.3. This includes the server and the client.
add a comment |
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<AsyncClientEndpoint> 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<SimpleHttpResponse>() {
@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
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34823433%2fdoes-apache-or-some-other-client-java-implementation-support-http-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Jetty's provides two HTTP/2 Java client APIs. Both require Java 8 and the mandatory use of the ALPN, as explained here.
Low level APIs
These APIs are based on HTTP2Client, it's based on the HTTP/2 concepts of session and streams and uses listeners to be notified of the HTTP/2 frames that arrive from the server.
// Setup and start the HTTP2Client.
HTTP2Client client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
client.addBean(sslContextFactory);
client.start();
// Connect to the remote host to obtains a Session.
FuturePromise<Session> sessionPromise = new FuturePromise<>();
client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);
Session session = sessionPromise.get(5, TimeUnit.SECONDS);
// Use the session to make requests.
HttpFields requestFields = new HttpFields();
requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://webtide.com/"), HttpVersion.HTTP_2, requestFields);
HeadersFrame headersFrame = new HeadersFrame(metaData, null, true);
session.newStream(headersFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Response headers.
System.err.println(frame);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Response content.
System.err.println(frame);
callback.succeeded();
}
});
High Level APIs
Jetty's HttpClient
provides a way to use different transports, one of which is the HTTP/2 transport. Applications will use the higher level HTTP APIs, but underneath Jetty will use HTTP/2 to transport the HTTP semantic.
In this way, applications can use the high level APIs provided by HttpClient
transparently, and factor out what transport to use in configuration or startup code.
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
add a comment |
Jetty's provides two HTTP/2 Java client APIs. Both require Java 8 and the mandatory use of the ALPN, as explained here.
Low level APIs
These APIs are based on HTTP2Client, it's based on the HTTP/2 concepts of session and streams and uses listeners to be notified of the HTTP/2 frames that arrive from the server.
// Setup and start the HTTP2Client.
HTTP2Client client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
client.addBean(sslContextFactory);
client.start();
// Connect to the remote host to obtains a Session.
FuturePromise<Session> sessionPromise = new FuturePromise<>();
client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);
Session session = sessionPromise.get(5, TimeUnit.SECONDS);
// Use the session to make requests.
HttpFields requestFields = new HttpFields();
requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://webtide.com/"), HttpVersion.HTTP_2, requestFields);
HeadersFrame headersFrame = new HeadersFrame(metaData, null, true);
session.newStream(headersFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Response headers.
System.err.println(frame);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Response content.
System.err.println(frame);
callback.succeeded();
}
});
High Level APIs
Jetty's HttpClient
provides a way to use different transports, one of which is the HTTP/2 transport. Applications will use the higher level HTTP APIs, but underneath Jetty will use HTTP/2 to transport the HTTP semantic.
In this way, applications can use the high level APIs provided by HttpClient
transparently, and factor out what transport to use in configuration or startup code.
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
add a comment |
Jetty's provides two HTTP/2 Java client APIs. Both require Java 8 and the mandatory use of the ALPN, as explained here.
Low level APIs
These APIs are based on HTTP2Client, it's based on the HTTP/2 concepts of session and streams and uses listeners to be notified of the HTTP/2 frames that arrive from the server.
// Setup and start the HTTP2Client.
HTTP2Client client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
client.addBean(sslContextFactory);
client.start();
// Connect to the remote host to obtains a Session.
FuturePromise<Session> sessionPromise = new FuturePromise<>();
client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);
Session session = sessionPromise.get(5, TimeUnit.SECONDS);
// Use the session to make requests.
HttpFields requestFields = new HttpFields();
requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://webtide.com/"), HttpVersion.HTTP_2, requestFields);
HeadersFrame headersFrame = new HeadersFrame(metaData, null, true);
session.newStream(headersFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Response headers.
System.err.println(frame);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Response content.
System.err.println(frame);
callback.succeeded();
}
});
High Level APIs
Jetty's HttpClient
provides a way to use different transports, one of which is the HTTP/2 transport. Applications will use the higher level HTTP APIs, but underneath Jetty will use HTTP/2 to transport the HTTP semantic.
In this way, applications can use the high level APIs provided by HttpClient
transparently, and factor out what transport to use in configuration or startup code.
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
Jetty's provides two HTTP/2 Java client APIs. Both require Java 8 and the mandatory use of the ALPN, as explained here.
Low level APIs
These APIs are based on HTTP2Client, it's based on the HTTP/2 concepts of session and streams and uses listeners to be notified of the HTTP/2 frames that arrive from the server.
// Setup and start the HTTP2Client.
HTTP2Client client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
client.addBean(sslContextFactory);
client.start();
// Connect to the remote host to obtains a Session.
FuturePromise<Session> sessionPromise = new FuturePromise<>();
client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise);
Session session = sessionPromise.get(5, TimeUnit.SECONDS);
// Use the session to make requests.
HttpFields requestFields = new HttpFields();
requestFields.put("User-Agent", client.getClass().getName() + "/" + Jetty.VERSION);
MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://webtide.com/"), HttpVersion.HTTP_2, requestFields);
HeadersFrame headersFrame = new HeadersFrame(metaData, null, true);
session.newStream(headersFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter()
{
@Override
public void onHeaders(Stream stream, HeadersFrame frame)
{
// Response headers.
System.err.println(frame);
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback)
{
// Response content.
System.err.println(frame);
callback.succeeded();
}
});
High Level APIs
Jetty's HttpClient
provides a way to use different transports, one of which is the HTTP/2 transport. Applications will use the higher level HTTP APIs, but underneath Jetty will use HTTP/2 to transport the HTTP semantic.
In this way, applications can use the high level APIs provided by HttpClient
transparently, and factor out what transport to use in configuration or startup code.
// Setup and start HttpClient with HTTP/2 transport.
HTTP2Client http2Client = new HTTP2Client();
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
httpClient.start();
// Make a request.
ContentResponse response = httpClient.GET("https://webtide.com/");
edited Jan 16 '16 at 17:25
answered Jan 16 '16 at 11:09
sbordetsbordet
10.6k2527
10.6k2527
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
add a comment |
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
There is no error reporting for the jetty API ... It just hangs ... Even the example you have provided above hangs (High level API)
– Neeraj Krishna
Jan 16 '16 at 14:12
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I forgot to mention the ALPN requirement. I have updated the answer with a link to the ALPN documentation section.
– sbordet
Jan 16 '16 at 17:25
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
I finally went with netty as there is no ALPN support needed for this
– Neeraj Krishna
Mar 22 '17 at 15:33
add a comment |
There is OkHttp: An HTTP & HTTP/2 client for Android and Java applications.
add a comment |
There is OkHttp: An HTTP & HTTP/2 client for Android and Java applications.
add a comment |
There is OkHttp: An HTTP & HTTP/2 client for Android and Java applications.
There is OkHttp: An HTTP & HTTP/2 client for Android and Java applications.
answered Jan 16 '16 at 4:43
marcospereiramarcospereira
10.4k33544
10.4k33544
add a comment |
add a comment |
Jetty has support for HTTP2 starting from version 9.3. This includes the server and the client.
add a comment |
Jetty has support for HTTP2 starting from version 9.3. This includes the server and the client.
add a comment |
Jetty has support for HTTP2 starting from version 9.3. This includes the server and the client.
Jetty has support for HTTP2 starting from version 9.3. This includes the server and the client.
answered Jan 16 '16 at 4:26
Mateusz DymczykMateusz Dymczyk
11.5k74884
11.5k74884
add a comment |
add a comment |
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<AsyncClientEndpoint> 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<SimpleHttpResponse>() {
@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
add a comment |
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<AsyncClientEndpoint> 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<SimpleHttpResponse>() {
@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
add a comment |
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<AsyncClientEndpoint> 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<SimpleHttpResponse>() {
@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
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<AsyncClientEndpoint> 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<SimpleHttpResponse>() {
@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
answered Nov 16 '18 at 14:02
ZyberZyber
12111
12111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34823433%2fdoes-apache-or-some-other-client-java-implementation-support-http-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown