use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class AsyncFullDuplexClientExample 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
// Disable 'Expect: Continue' handshake some servers cannot handle well
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setHttpProcessor(HttpProcessors.customClient(null).addLast((HttpRequestInterceptor) (request, entity, context) -> request.removeHeaders(HttpHeaders.EXPECT)).build()).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 URI requestUri = new URI("http://httpbin.org/post");
final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
final CountDownLatch latch = new CountDownLatch(1);
requester.execute(new AsyncClientExchangeHandler() {
@Override
public void releaseResources() {
requestProducer.releaseResources();
responseConsumer.releaseResources();
latch.countDown();
}
@Override
public void cancel() {
System.out.println(requestUri + " cancelled");
}
@Override
public void failed(final Exception cause) {
System.out.println(requestUri + "->" + cause);
}
@Override
public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
requestProducer.sendRequest(channel, httpContext);
}
@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 httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
}
@Override
public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
System.out.println(requestUri + "->" + response.getCode());
responseConsumer.consumeResponse(response, entityDetails, httpContext, 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);
}
}, Timeout.ofSeconds(30), HttpCoreContext.create());
latch.await(1, TimeUnit.MINUTES);
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class JSSEProviderIntegrationTest method testSimpleGet.
@Test
public void testSimpleGet() throws Exception {
server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
final InetSocketAddress serverEndpoint = server.start();
client.start();
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
final ClientSessionEndpoint streamEndpoint = connectFuture.get();
for (int i = 0; i < REQ_NUM; i++) {
final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result);
final HttpResponse response1 = result.getHead();
final String entity1 = result.getBody();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
Assertions.assertEquals("Hi there", entity1);
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project httpcomponents-core by apache.
the class JSSEProviderIntegrationTest method testSimpleGetConnectionClose.
@Test
public void testSimpleGetConnectionClose() throws Exception {
server.register("/hello", () -> new SingleLineResponseHandler("Hi there"));
final InetSocketAddress serverEndpoint = server.start();
client.start();
final URI requestURI = createRequestURI(serverEndpoint, "/hello");
for (int i = 0; i < REQ_NUM; i++) {
final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
try (final ClientSessionEndpoint streamEndpoint = connectFuture.get()) {
final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(AsyncRequestBuilder.get(requestURI).addHeader(HttpHeaders.CONNECTION, "close").build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
Assertions.assertNotNull(result);
final HttpResponse response1 = result.getHead();
final String entity1 = result.getBody();
Assertions.assertNotNull(response1);
Assertions.assertEquals(200, response1.getCode());
Assertions.assertEquals("Hi there", entity1);
}
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer in project OpenLineage by OpenLineage.
the class OpenLineageClient method executeAsync.
protected <T> CompletableFuture<ResponseMessage<T>> executeAsync(HttpRequest request, Object obj, TypeReference<T> ref) {
addAuthToReqIfKeyPresent(request);
try {
String jsonBody = objectMapper.writeValueAsString(obj);
final AsyncRequestProducer requestProducer = new BasicRequestProducer(request, AsyncEntityProducers.create(jsonBody, ContentType.APPLICATION_JSON));
Future<Message<HttpResponse, String>> future = http.execute(requestProducer, new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
return CompletableFuture.supplyAsync(() -> {
try {
Message<HttpResponse, String> message = future.get();
return createMessage(message, ref);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}, executorService);
} catch (JsonProcessingException e) {
log.error("Could not serialize to json object - {}", obj);
CompletableFuture<ResponseMessage<T>> completableFuture = new CompletableFuture<>();
completableFuture.completeExceptionally(e);
return completableFuture;
}
}
use of org.apache.hc.core5.http.nio.support.BasicResponseConsumer 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);
}
Aggregations