Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Spring: Unsupported Media Type with x-www-form-urlencoded body

I’m working on a REST API using Spring and I’m trying to implement a POST endpoint that receives x-www-form-urlencoded data in it’s body. This is my controller method so far:

@PostMapping(value = "/v1/contracts", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Object> fetchFilteredContracts(
        @RequestBody FilterObj body,
        @RequestParam(required = false) String number,
        @RequestParam(required = false) String supplierNumber
) {
    List<DataTableFilter.ColumnFilter> columnFilters = new ArrayList<>();

    if (number != null) {
        columnFilters.add(new DataTableFilter.ColumnFilter("number", number));
    }

    if (supplierNumber != null) {
        columnFilters.add(new DataTableFilter.ColumnFilter("supplierNumber", supplierNumber));
    }

    // Additional code not implemented yet

    return new ResponseEntity<>(HttpStatus.OK);
}

And just to explain further, this is my FilterObj:

public record FilterObj(
        String search_mode
) {}

I am using Postman to call this endpoint bit I get 415: Unsupported Media Type. See image.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

NOTE: If I remove the @RequestBody FilterObj body annotation from the method parameters it works fine, but then I don’t have access to the body object.

What am I doing wrong here?

>Solution :

@RequestBody will expect JSON/XML as body, and if you are sending key/value pairs then you need to either use @ModelAttribute to bind directly to your FilterObj or use MultiValueMap to (sort of manually) parse pairs and use them in your controller.

Or, if you control the client of your REST service, then use json to send objects to your endpoint.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading