简体   繁体   中英

How to enable multiple Content-Types for a response in spring-mvc?

I have a simple @RestController and would like to response with both JSON or XML depending on the http header content-type .

Problem: I'm always only getting XML response, never JSON. Of course I'm using Content-Type: application/json as http header.

What might be missing in the following configuration?

@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>

Interestingly: if I switch the produces statement: produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) , then I'm always getting JSON out and never XML !

So the question is: why does the first MediaType always have precedence, and the http header is never taken into account?

In your case, you should use Accept header not Content-Type .

On a request, the Accept header is used to request the Content-Type of the response from the server.

On a request the Content-Type is used to define the structure of the request body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM