Micronaut 響應(yīng) Content-Type

2023-03-06 13:40 更新

默認(rèn)情況下,Micronaut 控制器操作會(huì)生成 application/json。但是,您可以使用 @Produces 注釋或 HTTP 方法注釋的 produces 成員更改響應(yīng)的 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. 默認(rèn)內(nèi)容類型是 JSON

  2. 使用@Produces 注釋控制器操作以更改響應(yīng)內(nèi)容類型。

  3. 設(shè)置方法注釋的 produces 成員也會(huì)更改內(nèi)容類型。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)