RestController中的Spring RequestMapping返回406

时间:2018-10-16 05:39:29

标签: java spring spring-restcontroller http-status-code-406

@RestController内,我有一个@RequestMapping可以正常工作,除了在尝试返回POJO类ResponseVO的客户端中获得406之外

@RequestMapping(value = "path", method = RequestMethod.POST
            , produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<GenericResponse> path(

...
ResponseVO responseVO = new responseVO();
return new ResponseEntity<>(responseVO, HttpStatus.OK);

我正在发送带有JSON正文的POST,我的请求标头是

Connection: keep-alive
Content-Type: application/json
Accept: */*
Content-Length: 58
Host: localhost:8080
User-Agent: Apache-HttpClient/4.5.6 (Java/1.8.0_151)

响应头:

HTTP/1.1 406 Not Acceptable
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, DELETE
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 1067

3 个答案:

答案 0 :(得分:3)

在使用@RestController时,它自动意味着您在春季启动时注释了@Controller@ResponseBody。因此,您无需在方法上显式添加@ResponseBody批注。同样,在方法上方添加了@ResponseBody注释,而不是方法声明。因此,即使您正确添加此注释,您的代码也可以正常工作。在下面看看。

@RequestMapping(value = "path", method = RequestMethod.POST, produces =MediaType.APPLICATION_JSON_VALUE)
@ResponseBody 
public ResponseEntity<GenericResponse> path(

...
    ResponseVO responseVO = new responseVO();
    return new ResponseEntity<>(responseVO, HttpStatus.OK);

答案 1 :(得分:1)

首先,从方法中删除@ResponseBody注释,因为它已包含在@RestController注释中。同时从produces中删除@RequestMapping属性,并检查问题是否消失。

答案 2 :(得分:1)

您没有在consumes中设置@RequestMapping属性。

但是您可以将@PostMapping用于JSON,默认情况下将设置所有值。

@PostMapping("path")