6.7 The HttpRequest and HttpResponse
If you need more control over request processing then you can instead write a method that receives the complete HttpRequest.
In fact, there are several higher level interfaces that can be bound to method parameters of controllers. These include:
Interface | Description | Example |
---|---|---|
The full |
| |
All HTTP headers present in the request |
| |
All HTTP parameters (either from URI variables or request parameters) present in the request |
| |
All the Cookies present in the request |
|
The HttpRequest should be declared parametrized with a concrete generic type if the request body is needed, e.g. HttpRequest<MyClass> request . The body may not be available from the request otherwise. |
In addition, for full control over the emitted HTTP response you can use the static factory methods of the HttpResponse class which return a MutableHttpResponse.
The following example implements the previous MessageController
example using the HttpRequest and HttpResponse objects:
Request and Response Example
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/request")
public class MessageController {
@Get("/hello") (1)
public HttpResponse<String> hello(HttpRequest<?> request) {
String name = request.getParameters()
.getFirst("name")
.orElse("Nobody"); (2)
return HttpResponse.ok("Hello " + name + "!!")
.header("X-My-Header", "Foo"); (3)
}
}
Request and Response Example
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller("/request")
class MessageController {
@Get("/hello") (1)
HttpResponse<String> hello(HttpRequest<?> request) {
String name = request.getParameters()
.getFirst("name")
.orElse("Nobody") (2)
HttpResponse.ok("Hello " + name + "!!")
.header("X-My-Header", "Foo") (3)
}
}
Request and Response Example
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller("/request")
class MessageController {
@Get("/hello") (1)
fun hello(request: HttpRequest<*>): HttpResponse<String> {
val name = request.parameters
.getFirst("name")
.orElse("Nobody") (2)
return HttpResponse.ok("Hello $name!!")
.header("X-My-Header", "Foo") (3)
}
}
1 | The method is mapped to the URI /hello and accepts a HttpRequest |
2 | The HttpRequest is used to obtain the value of a query parameter called name . |
3 | The HttpResponse.ok(T) method is used to return a MutableHttpResponse with a text body. A header called X-My-Header is also added to the response object. |
HttpRequest is also available from static context via ServerRequestContext.
Generally ServerRequestContext is available within reactive flow, but the recommended approach is to propagate the necessary state through lambdas. |