The web client API
The Vert.x core library offers a createHttpClient
method from the vertx
context object. Instances of io.vertx.core.http.HttpClient
provides low-level methods for doing all kinds of HTTP requests with a fine-grained control over the protocol and the stream of events.
The web client API provides a simpler facade, especially for simplifying the payload data (un)marshaling. This API comes in the form of a new dependency:
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>${vertx.version}</version>
</dependency>
The following is a sample usage from a unit test. The test starts a HTTP server and then it does a HTTP GET request with the web client API to check that the request to the server succeeded:
@Test
public void start_http_server(TestContext context) {
Async async = context.async();
vertx.createHttpServer().requestHandler(req ->
req.response().putHeader("Content-Type", "text/plain").end("Ok"))
.listen(8080, context.asyncAssertSuccess(server -> {
WebClient webClient = WebClient.create(vertx);
webClient.get(8080, "localhost", "/").send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
context.assertTrue(response.headers().contains("Content-Type"));
context.assertEquals("text/plain", response.getHeader("Content-Type"));
context.assertEquals("Ok", response.body().toString());
webClient.close();
async.complete();
} else {
async.resolve(Promise.failedPromise(ar.cause()));
}
});
}));
}