我们如何将 returns (@Produces) 的相同 @Path 称为不同的格式?

How can we call the same @Path that returns (@Produces) a different format?

我有两条路径:

   @Path("Rectangle")
   @GET
   @Produces("application/xml")
   @Consumes("application/xml")

并且,

   @Path("Rectangle")
   @GET
   @Produces("application/json")
   @Consumes("application/xml")

当我在本地主机上点击 API 时,我总是得到 XML 响应。我需要做什么才能得到相同 @Path 的 JSON 响应?

根据 docs 您可以为同一终点指定多个 content-types

@Produces({"application/xml", "application/json"})

并且根据请求 header Accept 响应将有最被接受的 content-type

因此,您需要一种方法,它应该如下所示

@Path("Rectangle")
@GET
@Produces({"application/xml", "application/json"})
@Consumes("application/xml")

现在客户端需要发送 header Accept 以及他们想要接收的内容类型,例如:

Accept: application/xml

这将导致响应 header "content-type" 为 content-type: application/xml

您还可以使用 Accept header 来格式化您的回复