我正在使用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,因此解决了一个问题。现在,剩下的唯一问题是如何在响应中设置标题??
答案 0 :(得分:4)
这个问题在这里得到解答: In Spring MVC, how can I set the mime type header when using @ResponseBody
的代码示例@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) {
....
}
}