ResponseEntity doesnot accept text/csv: SpringBoot

Iam trying to create an API that accept both files like CSV and json body request. I tried using ResponseEntity object in spring boot.

The endpoint looks as below.

    @PostMapping(value="/csv",consumes=MediaType.ALL_VALUE)
    public void createConsumer(RequestEntity<?> data){



    }

The content headers is set via postman.

The Content-Type is text/csv and Accept is */*.

The error thrown is

2021-03-12 19:28:10.344  WARN 5780 --- [nio-8089-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/csv' not supported]

How can I solve this?

Answer

Write 2 methods. If you use file as request body, use MulpartFile and corresponding ‘consumes=..’, and for json use @RequestBody:

  @PostMapping(value="/csv", consumes = MULTIPART_FORM_DATA_VALUE)
        public void createConsumer(@RequestParam MultipartFile file){
          
        }

@PostMapping(value="/csv", consumes = APPLICATION_JSON_VALUE)
        public void createConsumerFromJson(@RequestBody SomeObject json){
          
        }

Set content type as form-data in body in Postman for MultipartFile, like

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *