1

I am currently porting an old API to Spring Boot and have encountered a problem. In the old API, two types of cURL requests could be made to the same endpoint: one for posting JSON data, and the other for posting JSON data with a file. The two requests look like such:

JSON Only:

curl -i -X POST 'http://localhost:8080/myEndpoint' \
-H 'Accept:application/json' \
-H 'someheader:value' \
-H 'Content-Type:application/json' \
-d '{ "jsondata":"goesHere" }'

JSON with image:

curl -i -X POST 'http://localhost:8080/myEndpoint' \
-H 'Accept: application/json' \
-H 'Content-Type: multipart/mixed' \
-H 'someheader:value' \ 
-F '{ "jsondata":"goesHere" }' \
-F "[email protected]" 

As can been seen, I can either send a Request Body or a Multipart/Mixed request to the same endpoint, and depending on what is received, the server will execute some business logic.

I have tried to replicate this behavior is spring to little avail. I am able to replicate the JSON only request with ease:

@RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public ResponseEntity createActivityFile(@RequestHeader(value = "someheader") String someheader,
                                         @RequestBody() String body,) {
    // do something...
    return new ResponseEntity(HttpStatus.OK);
}

The trouble arises when I add a multipart file to the mix. I've tried:

@RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public ResponseEntity createActivityFile(@RequestHeader(value = "someheader") String someheader,
                                         @RequestBody() String body,
                                         @RequestPart(value = "file", required = false) MultipartFile file) {
    // do something...
    return new ResponseEntity(HttpStatus.OK);
}

But with this, I always get a The request was rejected because no multipart boundary was found error.

This leads me to ask, is what I am attempting to do possible with Spring Boot? If so, what would my RequestMapping look like?

1 Answer 1

2

You can do it by using @Consumes annotation

consumes = MediaType.APPLICATION_JSON

And other endpoint with different MediaType

Sign up to request clarification or add additional context in comments.

2 Comments

Just to clarify, I am using the same endpoint (/myEndpoint) and I will have two functions mapped to this endpoint, with the difference being their consumed MediaType?
I just tried it out and it works! However, your answer isn't suited for Spring Boot, which doesn't have @Consumes. Instead you add consumes = MediaType.APPLICATION_JSON to the @RequestMapping. If you update your answer, I'd be happy to accept it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.