在@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
答案 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")