我有一个简单的@RestController
,并希望根据http标头JSON
同时回复XML
或content-type
。
问题:我总是只获得XML
响应,而不是JSON。我当然使用Content-Type: application/json
作为http标头。
以下配置中可能缺少什么?
@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头从不被考虑在内?
答案 0 :(得分:6)
您应该使用Accept
标题Content-Type
。第一个是请求,第二个是响应。