Jonatan Nieto
Jonatan Nieto

Reputation: 35

Spring @RestController Get Request Content-Type to response json or html

how can I take request Content-Type value? We need this to print json response or Html respone. My code is this:

 @RestController
public class GestorController {
    @RequestMapping(value="/gestores", method = RequestMethod.GET)  
    public Object gestoresHtml(@RequestParam(value="name", required=false, defaultValue="sh14") String name) throws Exception {
        String json = "prueba json";

        String contentType = ?????

        if(contentType.equals("application/json")){
            return json;
        }else{
            ModelAndView mav = new ModelAndView();
            mav.setViewName("gestores");
            mav.addObject("name", name);
            return mav;
        }
    }
}

Thanks for all.

Upvotes: 2

Views: 13888

Answers (1)

Nikolay Rusev
Nikolay Rusev

Reputation: 4230

Content-Type is a request header and you can get with the following code:

    @RequestMapping("/display")
    public void display(@RequestHeader("Content-Type") String contentType)  {}

see spring's @RequestHeader docs

You don't need to do this manually. The thing that you need is Content negotiation. Which returns response type that will fit in your needs. See this post

Upvotes: 8

Related Questions