Spring获取接收到的正文的MediaType

时间:2019-04-17 15:26:17

标签: spring spring-boot spring-restcontroller media-type

this answer之后,我通过以下方式在控制器中设置了方法:

@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还是另一种,我需要表现不同,所以我需要知道我的params主体是否经过json或urlencoded。有办法吗?

1 个答案:

答案 0 :(得分:2)

您只需插入Content-Type标头即可。

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