我有一个简单的 @RestController
并希望根据 http header content- 使用
。JSON
或 XML
进行响应输入
问题:我总是只得到 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/