java Spring Rest 服务中的可选请求头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14447731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Optional Request Header in Spring Rest Service
提问by Freephone Panwal
I'm using Spring Restful web service & having request body with request header as shown below:
我正在使用 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) {
....
}
}
I want to pass one more optional request header called "X-MyHeader". How do I specify this optional request header in Spring rest service?
我想传递一个名为“X-MyHeader”的可选请求标头。如何在 Spring rest 服务中指定这个可选的请求头?
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??
更新:我刚刚发现我可以在请求标头中设置 required=false ,因此解决了一个问题。现在,剩下的唯一问题是如何在响应中设置标头?
采纳答案by Rafael Sisto
This question is answered here: In Spring MVC, how can I set the mime type header when using @ResponseBody
此处回答此问题: 在 Spring MVC 中,如何在使用 @ResponseBody 时设置 mime 类型标头
Here is a code sample from: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-httpentity
这是来自: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);
}