Http Headers
In this first example we are going to build a simple Veronica application to show how to work with Http headers
Here's a list of the required preliminary knowledge for this tutorial:
- Basic application initialization
- How to create a route
- How to initialize the application router
If you lack the preliminary knowledge, we advise you to go back to previous tutorials to get started. Here's a list of the topics that we are going to cover in this tutorial:
- Http headers manipulation
We are going to create an application that reads the Accept
Http header of the request, and returns three different responses depending on its content. Let's get started:
- First we need to define a simple route for our application
Route<Request, Response> route = Route.builder()
.requestHandler(req -> {
// TODO
return ok(Response.builder().build());
})
.build();
- We now need to implement our RequestHandler:
Route<Request, Response> route = Route.builder()
.requestHandler(req -> {
Response response;
switch (req.getHeaders().getFirst("accept").toLowerCase()) {
case "application/json":
response = Response.builder()
.body("{\"message\": \"Hello, world!\"}")
.build();
break;
case "text/html":
response = Response.builder()
.body("<h1>Hello, world!</h1>")
.build();
break;
default:
response = Response.builder()
.body("Hello, world!")
.build();
}
return ok(response);
})
.build();
- For completeness, we might also want to specify the
Content-Type
response header:
Route<Request, Response> route = Route.builder()
.requestHandler(req -> {
Response response;
switch (req.getHeaders().getFirst("accept").toLowerCase()) {
case "application/json":
response = Response.builder()
.body("{\"message\": \"Hello, world!\"}")
.header("Content-Type", "application/json")
.build();
break;
case "text/html":
response = Response.builder()
.body("<h1>Hello, world!</h1>")
.header("Content-Type", "text/html")
.build();
break;
default:
response = Response.builder()
.body("Hello, world!")
.header("Content-Type", "text/plain")
.build();
}
return ok(response);
})
.build();
- And now we build our application
Route<Request, Response> route = Route.builder()
.requestHandler(req -> {
Response response;
switch (req.getHeaders().getFirst("accept").toLowerCase()) {
case "application/json":
response = Response.builder()
.body("{\"message\": \"Hello, world!\"}")
.header("Content-Type", "application/json")
.build();
break;
case "text/html":
response = Response.builder()
.body("<h1>Hello, world!</h1>")
.header("Content-Type", "text/html")
.build();
break;
default:
response = Response.builder()
.body("Hello, world!")
.header("Content-Type", "text/plain")
.build();
}
return ok(response);
})
.build();
Router<Request, Response> router = Router.builder()
.fallbackRoute(route)
.build();
int port = 8000;
Application<Request, Response> app = Application.basic()
.port(port)
.router(router)
.build();
app.start();
Updated over 5 years ago