use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class H2CompatibilityTest method executeHttpBin.
void executeHttpBin(final HttpHost target) throws Exception {
{
System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***");
final List<Message<HttpRequest, AsyncEntityProducer>> requestMessages = Arrays.asList(new Message<>(new BasicHttpRequest(Method.GET, target, "/headers"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.GET, target, "/drip"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)));
for (final Message<HttpRequest, AsyncEntityProducer> message : requestMessages) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final HttpRequest request = message.getHead();
final AsyncEntityProducer entityProducer = message.getBody();
client.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), TIMEOUT, new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, request, response, Objects.toString(response.getFirstHeader("server")));
} else {
logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, request, null, "(cancelled)");
countDownLatch.countDown();
}
});
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
}
}
}
{
System.out.println("*** httpbin.org HTTP/1.1 pipelined request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT);
final AsyncClientEndpoint streamEndpoint = connectFuture.get();
final int n = 10;
final CountDownLatch countDownLatch = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
final HttpRequest request;
final AsyncEntityProducer entityProducer;
if (i % 2 == 0) {
request = new BasicHttpRequest(Method.GET, target, "/headers");
entityProducer = null;
} else {
request = new BasicHttpRequest(Method.POST, target, "/anything");
entityProducer = new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN);
}
streamEndpoint.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, request, response, "pipelined / " + response.getFirstHeader("server"));
} else {
logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, request, null, "(cancelled)");
countDownLatch.countDown();
}
});
}
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
}
}
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class H2ProtocolNegotiationTest method testForceHttp2.
@Test
public void testForceHttp2() throws Exception {
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
final ListenerEndpoint listener = future.get();
final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
requester.start();
final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
final Future<AsyncClientEndpoint> connectFuture = requester.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final Future<Message<HttpResponse, String>> resultFuture1 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message1, CoreMatchers.notNullValue());
final HttpResponse response1 = message1.getHead();
assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
assertThat(response1.getVersion(), CoreMatchers.equalTo(HttpVersion.HTTP_2));
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class H2ServerAndRequesterTest method testSequentialRequestsSameEndpoint.
@Test
public void testSequentialRequestsSameEndpoint() throws Exception {
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
final ListenerEndpoint listener = future.get();
final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
requester.start();
final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
final Future<AsyncClientEndpoint> endpointFuture = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint endpoint = endpointFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
try {
final Future<Message<HttpResponse, String>> resultFuture1 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message1, CoreMatchers.notNullValue());
final HttpResponse response1 = message1.getHead();
assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body1 = message1.getBody();
assertThat(body1, CoreMatchers.equalTo("some stuff"));
final Future<Message<HttpResponse, String>> resultFuture2 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message2, CoreMatchers.notNullValue());
final HttpResponse response2 = message2.getHead();
assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body2 = message2.getBody();
assertThat(body2, CoreMatchers.equalTo("some other stuff"));
final Future<Message<HttpResponse, String>> resultFuture3 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message3 = resultFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message3, CoreMatchers.notNullValue());
final HttpResponse response3 = message3.getHead();
assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body3 = message3.getBody();
assertThat(body3, CoreMatchers.equalTo("some more stuff"));
} finally {
endpoint.releaseAndReuse();
}
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class AsyncPipelinedRequestExecutionExample method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
// Create and start requester
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).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)");
}
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost target = new HttpHost("httpbin.org");
final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> message) {
latch.countDown();
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(requestUri + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(requestUri + " cancelled");
}
});
}
latch.await();
// Manually release client endpoint when done !!!
clientEndpoint.releaseAndDiscard();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class BenchmarkWorker method execute.
public void execute() {
if (requestCount.decrementAndGet() >= 0) {
AsyncClientEndpoint endpoint = endpointRef.get();
if (endpoint != null && !endpoint.isConnected()) {
endpoint.releaseAndDiscard();
endpoint = null;
}
if (endpoint == null) {
requester.connect(host, config.getSocketTimeout(), null, new FutureCallback<AsyncClientEndpoint>() {
@Override
public void completed(final AsyncClientEndpoint endpoint) {
endpointRef.set(endpoint);
endpoint.execute(createRequestProducer(), createResponseConsumer(), context, new FutureCallback<Void>() {
@Override
public void completed(final Void result) {
execute();
}
@Override
public void failed(final Exception cause) {
execute();
}
@Override
public void cancelled() {
completionLatch.countDown();
}
});
}
@Override
public void failed(final Exception cause) {
stats.incFailureCount();
if (config.getVerbosity() >= 1) {
System.out.println("Connect error: " + cause.getMessage());
}
execute();
}
@Override
public void cancelled() {
completionLatch.countDown();
}
});
} else {
stats.incKeepAliveCount();
endpoint.execute(createRequestProducer(), createResponseConsumer(), context, new FutureCallback<Void>() {
@Override
public void completed(final Void result) {
execute();
}
@Override
public void failed(final Exception cause) {
execute();
}
@Override
public void cancelled() {
completionLatch.countDown();
}
});
}
} else {
completionLatch.countDown();
}
}
Aggregations