springspring-bootspring-restcontrollermedia-type

Spring get MediaType of received body


Following this answer I've set my method in controller this way:

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

Now I need to behave differently according to my @RequestBody being of one MediaType or the other, so I need to know whether my params body is json o urlencoded. Is there a way to do this?


Solution

  • You can simply inject 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);
        }
    

    But I would suggest to split this method on two methods with different consumes values:

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