20

This will work:

@RequestMapping(value = "/test", method = RequestMethod.POST,
    headers = {"content-type=application/json"}) {
    .......
}

If I add another value to it like the following, then it will fail and tell me this:

The specified HTTP method is not allowed for the requested resource (Request method 'POST' not supported)

@RequestMapping(value = "/test", method = RequestMethod.POST,
    headers = {"content-type=application/json","content-type=application/xml"}) {
    .......
}


I guess this is because Spring thinks the two content type values have "AND" relationship but instead I want them to be "OR".

Any suggestions?

Thanks!

2 Answers 2

36

If you are using Spring 3.1.x. You can look at using consumes, produces attributes of @RequestMapping annotation. Here is the Spring blog post on the improvements:

http://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements/

Snippet from the doc above:

@RequestMapping(value="/pets", headers="Content-Type=application/json")
public void addPet(@RequestBody Pet pet, Model model) {
    // ...
}

is replaced by:

@RequestMapping(value="/pets", consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
    // ...
}

In addition, if you need multiple media types. You can do the following:

produces={"application/json", "application/xml"}

consumes={"application/json", "application/xml"}
Sign up to request clarification or add additional context in comments.

1 Comment

I have a doubt here - when I write produces = "application/xml", still it gives me the error 406. But if write produces = "application/xml", headers = { "Content-Type=application/xml" }, then everything works fine. So my question is why produces is not enough to return XML response and need headers to complete the task.
22

Have you tried doing content-type=application/json,application/xml?

Not sure if it would work but putting two content-type headers in there I think only one will win.

OR

possibily use two RequestMapping annotations on the same method with different content-type headers?

2 Comments

"content-type=application/json,application/xml" worked! Thanks!
@dave G only one @RequestMapping is accepted by method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.