如何在Spring MVC REST控制器中获取HTTP标头信息?

11 浏览
0 Comments

如何在Spring MVC REST控制器中获取HTTP标头信息?

我对Web编程还比较新,特别是对Java,所以我才刚学会什么是头文件和正文。

我正在使用Spring MVC编写RESTful服务。我能够在我的控制器中使用@ RequestMapping创建简单的服务。我需要帮助了解如何从请求中获取HTTP头信息,该请求在我的REST服务控制器方法中。

我想解析头文件并从中获取一些属性。你能解释一下我如何获取这些信息吗?

admin 更改状态以发布 2023年5月23日
0
0 Comments

您可以使用@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);
    // ...
}

0
0 Comments

当您使用@RequestHeader注释参数时,参数会检索头信息。因此,您可以像这样执行操作:

@RequestHeader("Accept")

来获取Accept 头信息。

所以,从文档中得知:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {
}

Accept-EncodingKeep-Alive头值在encodingkeepAlive参数中分别提供。

不用担心。我们都是新手。

0