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

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

Rest - Same MediaType in response as in request

问题

  1. 我有一个消耗 `XML` `JSON` 的网络服务。<br>
  2. 目前输出总是以 `XML` 的形式呈现。<br>
  3. 是否可能将响应产生为与消耗的 `MediaType` 相同的 `MediaType`
  4. **我需要的是:**<br>
  5. 请求是 `XML`,响应也是 `XML`。<br>
  6. 请求是 `JSON`,响应也是 `JSON`
  7. **我的代码:**
  8. ```java
  9. @Path("/calculate")
  10. public class CalculationService
  11. {
  12. @POST
  13. @Path("/magic")
  14. @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
  15. @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
  16. public Output calculate(Input input)
  17. {
  18. Output output = new Output();
  19. output.setValue1(...);
  20. output.setValue2(...);
  21. output.setValue3(...);
  22. return output;
  23. }
  24. }
  1. <details>
  2. <summary>英文:</summary>
  3. I have a web service that consumes `XML` and `JSON`. &lt;br&gt;
  4. The output is currently always in `XML`.&lt;br&gt;
  5. Is it possible to produce the response in the same `MediaType` as the `MediaType` that was consumed?
  6. **What i need is:**&lt;br&gt;
  7. The request is `XML`, the response is `XML` too.&lt;br&gt;
  8. The request is `JSON`, the response is `JSON` too.
  9. **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(...);

  1. return output;
  2. }

}

  1. </details>
  2. # 答案1
  3. **得分**: 0
  4. 默认情况下,Web服务以 `MediaType.APPLICATION_XML` 形式提供响应。
  5. 可以通过设置 **Accept-Header** 来控制媒体类型。
  6. 通过设置值 `Accept: application/json`,响应将以 `MediaType.APPLICATION_JSON` 形式提供。
  7. <details>
  8. <summary>英文:</summary>
  9. By default, the Web service delivers the response as `MediaType.APPLICATION_XML`.
  10. The MediaType can be controlled by setting the **Accept-Header**.
  11. By setting the value `Accept: application/json`, the response is delivered as `MediaType.APPLICATION_JSON`.
  12. </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:

确定