use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class ReactiveFullDuplexClientExample method main.
public static void main(final String[] args) throws Exception {
String endpoint = "http://localhost:8080/echo";
if (args.length >= 1) {
endpoint = args[0];
}
// Create and start requester
final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).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 Random random = new Random();
final Flowable<ByteBuffer> publisher = Flowable.range(1, 100).map(ignored -> {
final String str = random.nextDouble() + "\n";
return ByteBuffer.wrap(str.getBytes(UTF_8));
});
final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(new URI(endpoint)).setEntity(new ReactiveEntityProducer(publisher, -1, ContentType.TEXT_PLAIN, null)).build();
final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
final Future<Void> responseComplete = requester.execute(requestProducer, consumer, Timeout.ofSeconds(30), null);
final Message<HttpResponse, Publisher<ByteBuffer>> streamingResponse = consumer.getResponseFuture().get();
System.out.println(streamingResponse.getHead());
for (final Header header : streamingResponse.getHead().getHeaders()) {
System.out.println(header);
}
System.out.println();
Observable.fromPublisher(streamingResponse.getBody()).map(byteBuffer -> {
final byte[] string = new byte[byteBuffer.remaining()];
byteBuffer.get(string);
return new String(string);
}).materialize().forEach(System.out::println);
responseComplete.get(1, TimeUnit.MINUTES);
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class H2RequestExecutionExample method main.
public static void main(final String[] args) throws Exception {
// Create and start requester
final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost target = new HttpHost("nghttp2.org");
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 Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
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) {
clientEndpoint.releaseAndReuse();
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
latch.countDown();
}
@Override
public void failed(final Exception ex) {
clientEndpoint.releaseAndDiscard();
System.out.println(requestUri + "->" + ex);
latch.countDown();
}
@Override
public void cancelled() {
clientEndpoint.releaseAndDiscard();
System.out.println(requestUri + " cancelled");
latch.countDown();
}
});
}
latch.await();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class H2ViaHttp1ProxyExecutionExample method main.
public static void main(final String[] args) throws Exception {
// Create and start requester
final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.NEGOTIATE).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)");
}
}
}).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost proxy = new HttpHost("localhost", 8888);
final HttpHost target = new HttpHost("https", "nghttp2.org");
final ComplexFuture<AsyncClientEndpoint> tunnelFuture = new ComplexFuture<>(null);
tunnelFuture.setDependency(requester.connect(proxy, Timeout.ofSeconds(30), null, new FutureContribution<AsyncClientEndpoint>(tunnelFuture) {
@Override
public void completed(final AsyncClientEndpoint endpoint) {
if (endpoint instanceof TlsUpgradeCapable) {
final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, proxy, target.toHostString());
endpoint.execute(new BasicRequestProducer(connect, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), new FutureContribution<Message<HttpResponse, Void>>(tunnelFuture) {
@Override
public void completed(final Message<HttpResponse, Void> message) {
final HttpResponse response = message.getHead();
if (response.getCode() == HttpStatus.SC_OK) {
((TlsUpgradeCapable) endpoint).tlsUpgrade(target, new FutureContribution<ProtocolIOSession>(tunnelFuture) {
@Override
public void completed(final ProtocolIOSession protocolSession) {
System.out.println("Tunnel to " + target + " via " + proxy + " established");
tunnelFuture.completed(endpoint);
}
});
} else {
tunnelFuture.failed(new HttpException("Tunnel refused: " + new StatusLine(response)));
}
}
});
} else {
tunnelFuture.failed(new IllegalStateException("TLS upgrade not supported"));
}
}
}));
final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
try {
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
endpoint.execute(new BasicRequestProducer(Method.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> message) {
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
latch.countDown();
}
@Override
public void failed(final Exception ex) {
System.out.println(requestUri + "->" + ex);
latch.countDown();
}
@Override
public void cancelled() {
System.out.println(requestUri + " cancelled");
latch.countDown();
}
});
}
latch.await();
} finally {
endpoint.releaseAndDiscard();
}
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class H2CompatibilityTest method main.
public static void main(final String... args) throws Exception {
final HttpHost[] h2servers = new HttpHost[] { new HttpHost("http", "localhost", 8080), new HttpHost("http", "localhost", 8081) };
final HttpHost httpbin = new HttpHost("http", "localhost", 8082);
final H2CompatibilityTest test = new H2CompatibilityTest();
try {
test.start();
for (final HttpHost h2server : h2servers) {
test.executeH2(h2server);
}
test.executeHttpBin(httpbin);
} finally {
test.shutdown();
}
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class H2FullDuplexClientExample 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 H2Config h2Config = H2Config.custom().setPushEnabled(false).setMaxConcurrentStreams(100).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).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://nghttp2.org/httpbin/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();
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
Aggregations