15

我正在使用 Spring Restful Web 服务并具有带有请求标头的请求正文,如下所示:

@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 REST 服务中指定此可选请求标头?

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

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

4

2 回答 2

17

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) {
        ....
    }
}
于 2020-08-21T05:31:40.560 回答
4

这个问题在这里得到了回答: 在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型标头

下面是一个代码示例: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);
}
于 2013-01-22T15:51:19.493 回答