Spring Rest Service中的可选请求标头

时间:2013-01-21 21:40:32

标签: java web-services spring rest

我正在使用Spring Restful网络服务&请求正文包含请求标题,如下所示:

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

我想再传递一个名为“X-MyHeader”的可选请求标头。如何在Spring休息服务中指定此可选请求标头?

另外,如何在响应头中传递相同的值? 谢谢!

更新:我刚刚发现我可以在请求标头中设置required = false,因此解决了一个问题。现在,剩下的唯一问题是如何在响应中设置标题??

2 个答案:

答案 0 :(得分:4)

这个问题在这里得到解答: In Spring MVC, how can I set the mime type header when using @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);
}

答案 1 :(得分:2)

在您的required=false中使用@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) {
        ....
    }
}