membersound
membersound

Reputation: 86627

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?

Upvotes: 2

Views: 5975

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

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.

Upvotes: 8

Related Questions