Reputation: 3530
I have a Spring-Boot controller application that will be called by the front-end. The Spring-boot @PostMapping
would accept the XML
and JSON
. I want to call different methods based on the Content-Type
.
Is there a way to check what is the incoming content type?
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api")
public class MyController {
@PostMapping(value = "/generator", consumes = {"application/json", "application/xml"}, produces = "application/json")
public String generate(@RequestBody String input) {
try {
System.out.println("INPUT CONTENT TYPE : ");
if(contentType == "application/xml")
{
//Call Method-1
}else if(contentType == "application/json"){
//Call Method-2
}
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
As we can see the RestController
method accepts XML and JSON
. I want to check whats the incoming Content-type
is based on its need to make different decisions. Can someone please explain to me how to do it?
Please Note: I am aware that I can create different methods to handle XML and JSON but I would like to do it in a single method so it would be easy and efficient.
Upvotes: 0
Views: 3127
Reputation: 58872
Add RequestHeader with its name Content-type
:
public String generate(@RequestBody String input, @RequestHeader("Content-type") String contentType)
Annotation which indicates that a method parameter should be bound to a web request header.
Upvotes: 7
Reputation: 106
You can use
@RequestHeader Map<String, String> headers
inside param of your generate() methode for get all Header come from the client.
After that, just check the
Content-Type
value
Upvotes: 4