Web Services Spring Rest服务中的可选请求标头

1aaf6o9v  于 2022-11-15  发布在  Spring
关注(0)|答案(2)|浏览(150)

我使用的是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服务中指定这个可选请求头?
另外,我如何在响应头中传递相同的值?谢谢!
UPDATE:我刚刚发现我可以在请求头中设置required=false,这样一个问题就解决了。现在,剩下的唯一问题是我如何在响应中设置头?

wf82jlnq

wf82jlnq1#

@RequestHeader中使用required=false

@PostMapping("/mykey")
public ResponseEntity<String> getData(
  @RequestBody String body, 
  @RequestHeader(value = "Auth", required = false) String authorization)  {}
jyztefdp

jyztefdp2#

这个问题在这里得到了回答: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);
}

相关问题