简体   繁体   中英

Optional Request Header in Spring Rest Service

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??

Use required=false in your @RequestHeader :

@RequestMapping(value = "/mykey", method = RequestMethod.POST, 
consumes="applicaton/json")
public ResponseEntity<String> getData(@RequestBody String body, 
@RequestHeader(value = "Auth", required = false) String authorization)  {
    try {
   ....
    } catch (Exception e) {
        ....
    }
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM