java - 如何在 spring-mvc 中为响应启用多个内容类型?

标签 java json xml spring rest

我有一个简单的 @RestController 并希望根据 http header content- 使用 JSONXML 进行响应输入

问题:我总是只得到 XML 响应,从来没有 JSON。当然,我正在使用 Content-Type: application/json 作为 http header 。

以下配置中可能缺少什么?

@RestController
public void MyServlet {

    @RequestMapping(value = "test", method = RequestMethod.GET,
            produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public MyResponse test() {
        return new MyResponse();
    }
}

@XmlRootElement
public class MyResponse {
    private String test = "somevalue";
    //getter, setter
}

pom.xml:

       <!-- as advised in: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>woodstox-core-asl</artifactId>
        </dependency>

有趣的是:如果我切换 produces 语句: 产生 = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}), 然后我总是得到 JSON 而不是 XML!

所以问题是:为什么第一个 MediaType 总是优先,而 http header 从不考虑?

最佳答案

在您的情况下,您应该使用 Accept header 而不是 Content-Type

在请求中,Accept header 用于请求服务器响应的Content-Type

在请求中,Content-Type 用于定义请求正文的结构。

关于java - 如何在 spring-mvc 中为响应启用多个内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44330535/

相关文章:

PHP 调用另一个 PHP 页面进行 MySQL 查询(返回 JSON 数据)

java - 从字符串中检查对象类型

xml - 你如何进行 HTTP Put?

java - 日历的 getTime() 方法返回错误的时间

java - 使用 Web 服务时如何管理用户 session ?

javascript - 如何使用小写键将 JSON 解析为对象

javascript - Phaser.js : cannot read property '0' on tiled map layer

java - Spring MVC xml配置

OpenWrt/DD-WRT 上的 Java

java - 如何摆脱 GWT 应用程序内部框架上的双滚动条