Optional request header in Spring Recreation

I am using Spring Restful web service and having the request body with the 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 another additional request header called "X-MyHeader". How to specify this optional request header in Spring rest service?

Also, how to pass this value in the response header? Thank!

UPDATE: I just discovered that I can set require = false in the request header, so that one problem is resolved. Now the only problem remains how to set the title in the response

+5
source share
1 answer

: Spring MVC, mime @ResponseBody

: 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);
}
+3

All Articles