@RequestHeader

您可以使用 @RequestHeader 注解将请求头绑定到控制器中的方法参数。

You can use the @RequestHeader annotation to bind a request header to a method argument in a controller.

以下示例显示带标头的一个请求:

The following example shows a request with headers:

Host localhost:8080 Accept text/html,application/xhtml+xml,application/xml;q=0.9 Accept-Language fr,en-gb;q=0.7,en;q=0.3 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300

以下示例获取 Accept-EncodingKeep-Alive 标头的值:

The following example gets the value of the Accept-Encoding and Keep-Alive headers:

Java
@GetMapping("/demo")
public void handle(
		@RequestHeader("Accept-Encoding") String encoding, (1)
		@RequestHeader("Keep-Alive") long keepAlive) { (2)
	//...
}
1 Get the value of the Accept-Encoding header.
2 Get the value of the Keep-Alive header.
Kotlin
@GetMapping("/demo")
fun handle(
		@RequestHeader("Accept-Encoding") encoding: String, (1)
		@RequestHeader("Keep-Alive") keepAlive: Long) { (2)
	//...
}
3 Get the value of the Accept-Encoding header.
4 Get the value of the Keep-Alive header.

如果目标方法参数类型不是 String,则会自动应用类型转换。请参阅 Type Conversion

Type conversion is applied automatically if the target method parameter type is not String. See Type Conversion.

当在 Map<String, String>MultiValueMap<String, String>HttpHeaders 参数上使用 @RequestHeader 注释时,该映射会使用所有标头值填充。

When a @RequestHeader annotation is used on a Map<String, String>, MultiValueMap<String, String>, or HttpHeaders argument, the map is populated with all header values.

内置支持可用于将逗号分隔的字符串转换为字符串数组或集合或类型转换系统已知的其他类型。例如,使用 @RequestHeader("Accept") 注释的方法参数可以是 String 类型,但也可以是 String[]List<String> 类型。

Built-in support is available for converting a comma-separated string into an array or collection of strings or other types known to the type conversion system. For example, a method parameter annotated with @RequestHeader("Accept") may be of type String but also of String[] or List<String>.