Reputation: 133
How can I validate the accept headers in spring and return a custom message if the accept header is not application/json. Currently I am doing it this way(below) but I am wondering if there is another way of doing this?
I know I can make custom exceptions and throw the exception based on what went wrong but is there a different way of doing this?
@GetMapping(value = "/get", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<String> get(final HttpEntity<String> httpEntity) {
HttpHeaders responseHeaders = new HttpHeaders();
String acceptString = httpEntity.getHeaders().getFirst("Accept");
if (acceptString == null || acceptString.isEmpty()) {
return new ResponseEntity<String>("empty accept header", HttpStatus.BAD_REQUEST);
}
if ((MediaType.APPLICATION_JSON_VALUE).equalsIgnoreCase(acceptString)) {
responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
}
else {
return new ResponseEntity<String>("Not valid accept value", HttpStatus.BAD_REQUEST);
}
....
Upvotes: 2
Views: 1920
Reputation: 265
Within your @Getmapping
you can add headers="Accept=application/json"
this way your method will only handle calls with that header type.
You can then add a method which processes all the calls that are ignored by your specific AcceptHeader method. This way you only need one method to validate the headers.
You can also write a custom validator and use anotation to add this to your method like here: conditional validation
Upvotes: 1