英文:
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`. <br>
The output is currently always in `XML`.<br>
Is it possible to produce the response in the same `MediaType` as the `MediaType` that was consumed?
**What i need is:**<br>
The request is `XML`, the response is `XML` too.<br>
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论