如何访问 Spring MVC REST 控制器中的 HTTP 标头信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19556039/
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
How to get access to HTTP header information in Spring MVC REST controller?
提问by Horse Voice
I am new to web programming in general, especially in Java, so I just learned what a header and body is.
一般来说,我是 Web 编程的新手,尤其是 Java,所以我刚刚了解了 header 和 body 是什么。
I'm writing RESTful services using Spring MVC. I am able to create simple services with the @RequestMappingin my controllers. I need help understanding how to get HTTP header information from a request that comes to my method in my REST service controller. I would like to parse out the header and get some attributes from it.
我正在使用 Spring MVC 编写 RESTful 服务。我能够@RequestMapping在我的控制器中创建简单的服务。我需要帮助了解如何从我的 REST 服务控制器中的方法的请求中获取 HTTP 标头信息。我想解析标题并从中获取一些属性。
Could you explain how I go about getting that information?
你能解释一下我是如何获取这些信息的吗?
回答by Vidya
When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:
当您使用 注释参数时@RequestHeader,该参数将检索标头信息。所以你可以做这样的事情:
@RequestHeader("Accept")
to get the Acceptheader.
获取Accept标题。
So from the documentation:
所以从文档中:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}
The Accept-Encodingand Keep-Aliveheader values are provided in the encodingand keepAliveparameters respectively.
的Accept-Encoding和Keep-Alive在被提供标头值encoding和keepAlive参数分别。
And no worries. We are all noobs with something.
而且不用担心。我们都是菜鸟。
回答by Debojit Saikia
You can use the @RequestHeaderannotation with HttpHeadersmethod parameter to gain access to all request headers:
您可以使用@RequestHeader带有HttpHeaders方法参数的注释来访问所有请求标头:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
回答by Armando Cordova
My solution in Header parameters with example is user="test"is:
我在标题参数示例中的解决方案是user="test"是:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}

