Micronaut 响应 Content-Type

2023-03-06 13:40 更新

默认情况下,Micronaut 控制器操作会生成 application/json。但是,您可以使用 @Produces 注释或 HTTP 方法注释的 produces 成员更改响应的 Content-Type。

 Java Groovy  Kotlin 
import io.micronaut.context.annotation.Requires;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;

@Controller("/produces")
public class ProducesController {

    @Get // (1)
    public HttpResponse index() {
        return HttpResponse.ok().body("{\"msg\":\"This is JSON\"}");
    }

    @Produces(MediaType.TEXT_HTML)
    @Get("/html") // (2)
    public String html() {
        return "<html><title><h1>HTML</h1></title><body></body></html>";
    }

    @Get(value = "/xml", produces = MediaType.TEXT_XML) // (3)
    public String xml() {
        return "<html><title><h1>XML</h1></title><body></body></html>";
    }
}
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces

@Controller("/produces")
class ProducesController {

    @Get // (1)
    HttpResponse index() {
        HttpResponse.ok().body('{"msg":"This is JSON"}')
    }

    @Produces(MediaType.TEXT_HTML) // (2)
    @Get("/html")
    String html() {
        "<html><title><h1>HTML</h1></title><body></body></html>"
    }

    @Get(value = "/xml", produces = MediaType.TEXT_XML) // (3)
    String xml() {
        "<html><title><h1>XML</h1></title><body></body></html>"
    }
}
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces

@Controller("/produces")
class ProducesController {

    @Get // (1)
    fun index(): HttpResponse<*> {
        return HttpResponse.ok<Any>().body("{\"msg\":\"This is JSON\"}")
    }

    @Produces(MediaType.TEXT_HTML)
    @Get("/html") // (2)
    fun html(): String {
        return "<html><title><h1>HTML</h1></title><body></body></html>"
    }

    @Get(value = "/xml", produces = [MediaType.TEXT_XML]) // (3)
    fun xml(): String {
        return "<html><title><h1>XML</h1></title><body></body></html>"
    }
}
  1. 默认内容类型是 JSON

  2. 使用@Produces 注释控制器操作以更改响应内容类型。

  3. 设置方法注释的 produces 成员也会更改内容类型。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号