6.10 Response Content-Type

A Micronaut’s controller action produces application/json by default. Nonetheless you can change the Content-Type of the response with the @Produces annotation or the produces member of the HTTP method annotations.

  1. import io.micronaut.context.annotation.Requires;
  2. import io.micronaut.http.HttpResponse;
  3. import io.micronaut.http.MediaType;
  4. import io.micronaut.http.annotation.Controller;
  5. import io.micronaut.http.annotation.Get;
  6. import io.micronaut.http.annotation.Produces;
  7. @Controller("/produces")
  8. public class ProducesController {
  9. @Get (1)
  10. public HttpResponse index() {
  11. return HttpResponse.ok().body("{\"msg\":\"This is JSON\"}");
  12. }
  13. @Produces(MediaType.TEXT_HTML)
  14. @Get("/html") (2)
  15. public String html() {
  16. return "<html><title><h1>HTML</h1></title><body></body></html>";
  17. }
  18. @Get(value = "/xml", produces = MediaType.TEXT_XML) (3)
  19. public String xml() {
  20. return "<html><title><h1>XML</h1></title><body></body></html>";
  21. }
  22. }
  1. import io.micronaut.context.annotation.Requires
  2. import io.micronaut.http.HttpResponse
  3. import io.micronaut.http.MediaType
  4. import io.micronaut.http.annotation.Controller
  5. import io.micronaut.http.annotation.Get
  6. import io.micronaut.http.annotation.Produces
  7. @Controller("/produces")
  8. class ProducesController {
  9. @Get (1)
  10. HttpResponse index() {
  11. HttpResponse.ok().body("{\"msg\":\"This is JSON\"}")
  12. }
  13. @Produces(MediaType.TEXT_HTML) (2)
  14. @Get("/html")
  15. String html() {
  16. "<html><title><h1>HTML</h1></title><body></body></html>"
  17. }
  18. @Get(value = "/xml", produces = MediaType.TEXT_XML) (3)
  19. String xml() {
  20. return "<html><title><h1>XML</h1></title><body></body></html>"
  21. }
  22. }
  1. import io.micronaut.context.annotation.Requires
  2. import io.micronaut.http.HttpResponse
  3. import io.micronaut.http.MediaType
  4. import io.micronaut.http.annotation.Controller
  5. import io.micronaut.http.annotation.Get
  6. import io.micronaut.http.annotation.Produces
  7. @Controller("/produces")
  8. class ProducesController {
  9. @Get (1)
  10. fun index(): HttpResponse<*> {
  11. return HttpResponse.ok<Any>().body("{\"msg\":\"This is JSON\"}")
  12. }
  13. @Produces(MediaType.TEXT_HTML)
  14. @Get("/html") (2)
  15. fun html(): String {
  16. return "<html><title><h1>HTML</h1></title><body></body></html>"
  17. }
  18. @Get(value = "/xml", produces = [MediaType.TEXT_XML]) (3)
  19. fun xml(): String {
  20. return "<html><title><h1>XML</h1></title><body></body></html>"
  21. }
  22. }
1The default content type is JSON
2Annotate a controller’s action with @Produces to change the response content type.
3Setting the produces member of the method annotation also changes the content type.