I'm using Spring Restful web service & having request body with request header as shown below:
@RequestMapping(value = "/mykey", method = RequestMethod.POST, consumes="applicaton/json")
public ResponseEntity<String> getData(@RequestBody String body, @RequestHeader("Auth") String authorization) {
try {
....
} catch (Exception e) {
....
}
}
I want to pass one more optional request header called "X-MyHeader". How do I specify this optional request header in Spring rest service?
Also, how do I pass this same value in response header?? Thanks!
UPDATE: I just found that I can set required=false in request header, so one issue is resolved. Now, the only issue remaining is how do I set the header in the response??
To make the header optional, we can use the required attribute of @RequestHeader annotation. Next is an example of setting a default header value if a particular header is not present in the request. To set a default value, we can use the defaultValue attribute of the @RequestHeader annotation.
You can pass duplicate headers as well and there will not be any overwritten of values. For example, If we pass two values of header1 as value1 and value2 then it will be merged and will be passed as header1=value1 and header1=value2. It is the default behaviour.
@RequestHeader annotation binds request header values to method parameters. If the method parameter is Map<String, String> , MultiValueMap<String, String> , or HttpHeaders then the map is populated with all header names and values.
A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.
Use required=false
in your @RequestHeader
:
@PostMapping("/mykey")
public ResponseEntity<String> getData(
@RequestBody String body,
@RequestHeader(value = "Auth", required = false) String authorization) {}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With