相同的媒体类型在响应中和请求中。

huangapple go评论61阅读模式
英文:

Rest - Same MediaType in response as in request

问题

我有一个消耗 `XML` 和 `JSON` 的网络服务。<br>
目前输出总是以 `XML` 的形式呈现。<br>
是否可能将响应产生为与消耗的 `MediaType` 相同的 `MediaType`?

**我需要的是:**<br>
请求是 `XML`,响应也是 `XML`。<br>
请求是 `JSON`,响应也是 `JSON`。

**我的代码:**
```java
@Path("/calculate")
public class CalculationService
{
    @POST
    @Path("/magic")
    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Output calculate(Input input)
    {
        Output output = new Output();
        output.setValue1(...);
        output.setValue2(...);
        output.setValue3(...);
        
        return output;
    }
}

<details>
<summary>英文:</summary>

I have a web service that consumes `XML` and `JSON`. &lt;br&gt;
The output is currently always in `XML`.&lt;br&gt;
Is it possible to produce the response in the same `MediaType` as the `MediaType` that was consumed?

**What i need is:**&lt;br&gt;
The request is `XML`, the response is `XML` too.&lt;br&gt;
The request is `JSON`, the response is `JSON` too.

**My Code:**

@Path("/calculate")
public class CalculationService
{
@POST
@Path("/magic")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Output calculate(Input input)
{
Output output = new Output();
output.setValue1(...);
output.setValue2(...);
output.setValue3(...);

    return output;
}

}


</details>


# 答案1
**得分**: 0

默认情况下,Web服务以 `MediaType.APPLICATION_XML` 形式提供响应。

可以通过设置 **Accept-Header** 来控制媒体类型。

通过设置值 `Accept: application/json`,响应将以 `MediaType.APPLICATION_JSON` 形式提供。

<details>
<summary>英文:</summary>

By default, the Web service delivers the response as `MediaType.APPLICATION_XML`.

The MediaType can be controlled by setting the **Accept-Header**.

By setting the value `Accept: application/json`, the response is delivered as `MediaType.APPLICATION_JSON`.

</details>



huangapple
  • 本文由 发表于 2020年5月4日 20:32:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61592292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定