use of org.apache.hc.core5.util.Args 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.util.Args in project httpcomponents-core by apache.
the class AsyncRequestExecutionExample 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 CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
requester.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), Timeout.ofSeconds(5), 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();
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 AsyncServerFilterExample method main.
public static void main(final String[] args) throws Exception {
int port = 8080;
if (args.length >= 1) {
port = Integer.parseInt(args[0]);
}
final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractAsyncServerAuthFilter<String>(true) {
@Override
protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
return authorizationValue;
}
@Override
protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "let me pass".equals(challengeResponse);
}
@Override
protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
return "who goes there?";
}
}).addFilterFirst("my-filter", (request, entityDetails, context, responseTrigger, chain) -> {
if (request.getRequestUri().equals("/back-door")) {
responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_OK), AsyncEntityProducers.create("Welcome"));
return null;
}
return chain.proceed(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {
@Override
public void sendInformation(final HttpResponse response) throws HttpException, IOException {
responseTrigger.sendInformation(response);
}
@Override
public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
response.addHeader("X-Filter", "My-Filter");
responseTrigger.submitResponse(response, entityProducer);
}
@Override
public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
responseTrigger.pushPromise(promise, responseProducer);
}
});
}).register("*", new AsyncServerRequestHandler<Message<HttpRequest, String>>() {
@Override
public AsyncRequestConsumer<Message<HttpRequest, String>> prepare(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
}
@Override
public void handle(final Message<HttpRequest, String> requestMessage, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
// do something useful
responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hello").build(), context);
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP server shutting down");
server.close(CloseMode.GRACEFUL);
}));
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
final ListenerEndpoint listenerEndpoint = future.get();
System.out.print("Listening on " + listenerEndpoint.getAddress());
server.awaitShutdown(TimeValue.MAX_VALUE);
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class ClassicFileServerExample method main.
public static void main(final String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
// Document root directory
final String docRoot = args[0];
int port = 8080;
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
SSLContext sslContext = null;
if (port == 8443) {
// Initialize SSL context
final URL url = ClassicFileServerExample.class.getResource("/my.keystore");
if (url == null) {
System.out.println("Keystore not found");
System.exit(1);
}
sslContext = SSLContexts.custom().loadKeyMaterial(url, "secret".toCharArray(), "secret".toCharArray()).build();
}
final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).setSslContext(sslContext).setExceptionListener(new ExceptionListener() {
@Override
public void onError(final Exception ex) {
ex.printStackTrace();
}
@Override
public void onError(final HttpConnection conn, final Exception ex) {
if (ex instanceof SocketTimeoutException) {
System.err.println("Connection timed out");
} else if (ex instanceof ConnectionClosedException) {
System.err.println(ex.getMessage());
} else {
ex.printStackTrace();
}
}
}).register("*", new HttpFileHandler(docRoot)).create();
server.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
System.out.println("Listening on port " + port);
server.awaitTermination(TimeValue.MAX_VALUE);
}
use of org.apache.hc.core5.util.Args in project httpcomponents-core by apache.
the class ClassicPostExecutionExample method main.
public static void main(final String[] args) throws Exception {
final HttpRequester httpRequester = RequesterBootstrap.bootstrap().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)");
}
}
}).setSocketConfig(SocketConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).create();
final HttpCoreContext coreContext = HttpCoreContext.create();
final HttpHost target = new HttpHost("httpbin.org");
final HttpEntity[] requestBodies = { HttpEntities.create("This is the first test request", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the second test request".getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM), HttpEntities.create(outStream -> outStream.write(("This is the third test request " + "(streaming)").getBytes(StandardCharsets.UTF_8)), ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), HttpEntities.create("This is the fourth test request " + "(streaming with trailers)", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8), new BasicHeader("trailer1", "And goodbye")) };
final String requestUri = "/post";
for (int i = 0; i < requestBodies.length; i++) {
final ClassicHttpRequest request = ClassicRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
request.setEntity(requestBodies[i]);
try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
System.out.println(requestUri + "->" + response.getCode());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
}
}
}
Aggregations