2

如何获取请求 Content-Type 值?我们需要它来打印 json 响应或 Html 响应。我的代码是这样的:

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

谢谢大家。

4

1 回答 1

6

Content-Type是一个请求标头,您可以使用以下代码获取:

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

见春天的@RequestHeader 文档

您无需手动执行此操作。你需要的是Content negotiation. 它返回适合您需求的响应类型。看到这个帖子

于 2015-07-27T07:52:18.853 回答