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:

  1. <dependency>
  2. <groupId>io.vertx</groupId>
  3. <artifactId>vertx-web-client</artifactId>
  4. <version>${vertx.version}</version>
  5. </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:

  1. @Test
  2. public void start_http_server(TestContext context) {
  3. Async async = context.async();
  4. vertx.createHttpServer().requestHandler(req ->
  5. req.response().putHeader("Content-Type", "text/plain").end("Ok"))
  6. .listen(8080, context.asyncAssertSuccess(server -> {
  7. WebClient webClient = WebClient.create(vertx);
  8. webClient.get(8080, "localhost", "/").send(ar -> {
  9. if (ar.succeeded()) {
  10. HttpResponse<Buffer> response = ar.result();
  11. context.assertTrue(response.headers().contains("Content-Type"));
  12. context.assertEquals("text/plain", response.getHeader("Content-Type"));
  13. context.assertEquals("Ok", response.body().toString());
  14. webClient.close();
  15. async.complete();
  16. } else {
  17. async.resolve(Promise.failedPromise(ar.cause()));
  18. }
  19. });
  20. }));
  21. }