Vertx HTTP Servers

Reading Time: 3 minutes

Vert.x makes it easy to create an HTTP server for your application to receive HTTP requests. You can create one or more HTTP servers, depending on your need. In this tutorial we will look at how to create an HTTP server from within the verticle and how to handle requests.

Creating an HTTP server

Creating an HTTP server is done using the Vertx createHttpServer () example method. Here is an example of creating an HTTP server in Vert.x:

HttpServer httpServer = vertx.createHttpServer();

It is common to start an HTTP server from within a verticle. That way all the handlers registered on the HTTP server will be used by the same thread that started the verticle.

public class VertxHttpClientVerticle extends AbstractVerticle {
    @Override
    public void start() throws Exception {
        HttpClient httpClient = vertx.createHttpClient();
    }
}

Starting the HTTP Server

Once you have created an HTTP server, you can start it using its listening method (). Here’s what starting an HTTP server looks like:

public class VertxHttpServerVerticle extends AbstractVerticle {
    private HttpServer httpServer = null;
    @Override
    public void start() throws Exception {
        httpServer = vertx.createHttpServer();
        httpServer.listen(9999);
    }
}

The HttpServer section has many versions of the listen() method, giving you different options for launching the HTTP server.

Setting a Request Handler on the HTTP Server

To manage incoming HTTP requests you must set the request handler on the HTTP server. This is usually done before starting the server. Here is an example of a Vert.x HTTP server request handler example:

public class VertxHttpServerVerticle extends AbstractVerticle {

    private HttpServer httpServer = null;

    @Override
    public void start() throws Exception {
        httpServer = vertx.createHttpServer();

        httpServer.requestHandler(new Handler<HttpServerRequest>() {
            @Override
            public void handle(HttpServerRequest request) {
                System.out.println("incoming request!");
            }
        });

        httpServer.listen(9999);
    }
}

Each time an HTTP request arrives on the HTTP server, the handle() method of the Handler object is called. Within the handle() method you can use the code needed to manage the HTTP request.

Request Headers and Parameters

You can access HTTP headers and parameters from the HttpServerRequest object transmitted as a parameter in the handle() method. Here is an example showing how to access a few features of an HTTP request:

httpServer.requestHandler(new Handler<HttpServerRequest>() {
    @Override
    public void handle(HttpServerRequest request) {
        System.out.println("incoming request!");

        request.uri();
        request.path();
        request.getParam("p1");
    }
});

Handling POST Requests

If the HTTP request is an HTTP POST request you need to handle it separately. You need to attach the handler to the HTTP request. The body handler is called whenever data from the request body arrives. Here’s what it looks like:

httpServer.requestHandler(new Handler<HttpServerRequest>() {
    @Override
    public void handle(HttpServerRequest request) {
        System.out.println("incoming request!");

        if(request.method() == HttpMethod.POST){
            request.handler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buffer) {
                        
                }
            });
        }
    }
});

If you want to wait until the full HTTP POST body has arrived you can attach the end handler instead. The end handler is not called until the full HTTP POST body is accepted. However, the end handler does not have direct access to the full HTTP POST body. You need to collect that in the request handler. Here is an example of a Vert.x HTTP request end handler example that does all of this:

httpServer.requestHandler(new Handler<HttpServerRequest>() {

    @Override
    public void handle(HttpServerRequest request) {
        System.out.println("incoming request!");

        Buffer fullRequestBody = Buffer.buffer();
        if(request.method() == HttpMethod.POST){

            request.handler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buffer) {
                    fullRequestBody.appendBuffer(buffer);
                }
            }

            request.endHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buffer) {
                    // here you can access the 
                    // fullRequestBody Buffer instance.
                }
            });
        }
    }
});

Sending Back an HTTP Response

Yes you can send back HTTP response for an incoming HTTP request. To do so you need to find the HttpServerResponse instance in the request object. Here’s how to get the HttpServerResponse item:

HttpServerResponse response = request.response();

Once you have obtained a HttpServerResponse instance you can set the HTTP response status code and headers like this:

response.setStatusCode(200);
response.headers()
    .add("Content-Length", String.valueOf(57))
    .add("Content-Type", "text/html")
;

After writing the headers back you can write the response body back via the write() method, like this:

response.write("Vert.x is alive!");
response.end();

You can call the write() several times to add additional data to the response body. The write() method also exists in a version that takes the Vert.x Buffer instance as a parameter. This method will write content of the Buffer to the HTTP response.

The write() method is asynchronous and returns immediately after queuing a string or buffer.

When you have finished typing the HTTP response body you should stop the HTTP response. This is done by calling the end() method as shown in the previous example. You can also write an HTTP response body and end the response in a single method call, like this:

response.end("Vert.x is alive!");

The end() method can take either a String or Buffer as parameter. The parameter will be written to the response body, and the response ended after that.

Closing the HTTP Server

To close an HTTP server you simply call its close() method like this:

httpServer.close();

The close() method executes asynchronously, so the HTTP server may not be fully closed by the time the close() method returns. You can pass a close handler as parameter to the close() method, to be notified when the HTTP server is fully closed.

Written by 

Prakhar is a Software Consultant at Knoldus . He has completed his Masters of Computer Applications from Bharati Vidyapeeth Institute of Computer Applications and Management, Paschim Vihar . He likes problem solving and exploring new technologies .

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading