Spring 获取接收正文的 MediaType
Spring get MediaType of received body
在 之后,我在控制器中以这种方式设置了我的方法:
@PostMapping(path = PathConstants.START_ACTION, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params)
现在我需要根据我的 @RequestBody
是一种 MediaType 还是另一种 MediaType 来表现不同,所以我需要知道我的 params
正文是否是 json 或 urlencoded。有办法吗?
你可以简单地注入 Content-Type header.
@PostMapping(path = "/{processDefinitionId}", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> start(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params,
@RequestHeader("Content-Type") String contentType) {
if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
System.out.println("json");
} else {
// ...
}
return ResponseEntity.ok(params);
}
但我建议将此方法拆分为两种具有不同消耗值的方法:
@PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> startV2Json(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}
@PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> startV2UrlEncoded(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}
在
@PostMapping(path = PathConstants.START_ACTION, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<BaseResponse<ProcessInstance>> start(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params)
现在我需要根据我的 @RequestBody
是一种 MediaType 还是另一种 MediaType 来表现不同,所以我需要知道我的 params
正文是否是 json 或 urlencoded。有办法吗?
你可以简单地注入 Content-Type header.
@PostMapping(path = "/{processDefinitionId}", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> start(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params,
@RequestHeader("Content-Type") String contentType) {
if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
System.out.println("json");
} else {
// ...
}
return ResponseEntity.ok(params);
}
但我建议将此方法拆分为两种具有不同消耗值的方法:
@PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> startV2Json(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}
@PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> startV2UrlEncoded(@PathVariable String processDefinitionId,
@RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}