Optional Request Header in Spring Rest Service
This question is answered here: In Spring MVC, how can I set the mime type header when using @ResponseBody
Here is a code sample from: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-httpentity
@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader");
byte[] requestBody = requestEntity.getBody();
// do something with request header and body
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
Use required=false
in your @RequestHeader
:
@PostMapping("/mykey")
public ResponseEntity<String> getData(
@RequestBody String body,
@RequestHeader(value = "Auth", required = false) String authorization) {}