springMVC/SpringBoot中提供了@RequestHeader注解用来获取请求头。
一、使用@RequestHeader获取请求头
(一)获取某一个请求头
例如,获取accept-language请求头:
1
2
3
4
5
6
|
@GetMapping ( "/getLanguage" )
public Result test( @RequestHeader ( "accept-language" ) String language) {
// ......
return new Result( true , 600 , language);
}
|
使用postman,没有设置accept-language请求头时,响应:
1
2
3
4
5
6
7
|
{
"timestamp" : "2019-12-3T20:43:58.971+0000" ,
"status" : 400,
"error" : "Bad Request" ,
"message" : "Missing request header 'accept-language' for method parameter of type String" ,
"path" : "/getLanguage"
}
|
添加了accept-language请求头后,响应:
1
2
3
4
5
|
{
"flag" : true ,
"code" : 600,
"message" : "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}
|
(二)获取数值型请求头
1
2
3
4
|
@GetMapping ( "/num" )
public Result getNumber( @RequestHeader ( "my-number" ) int myNumber) {
return new Result( true , HttpStatus.OK.value(), String.valueOf(myNumber));
}
|
使用postman设置my-number请求头值为1,响应:
1
2
3
4
5
|
{
"flag" : true ,
"code" : 200,
"message" : "1"
}
|
(三)一次性获取所有请求头
1、使用Map接收所有请求头
1
2
3
4
5
6
7
8
|
@GetMapping ( "/getHeaders" )
public Result listAllHeaders( @RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> {
// 日志中输出所有请求头
logger.info(String.format( "Header '%s' = %s" , key, value));
});
return new Result( true , HttpStatus.OK.value(), "" );
}
|
使用postman请求该地址,控制台打印:
2019-12-03 21:10:35,993 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'user-agent' = PostmanRuntime/7.20.1
2019-12-03 21:10:35,994 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'accept' = */*
2019-12-03 21:10:35,994 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'cache-control' = no-cache
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'postman-token' = 47dce6dd-c082-47b0-8867-720e45205aa1
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'host' = localhost:10000
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'accept-encoding' = gzip, deflate
2019-12-03 21:10:35,996 INFO [http-nio-10000-exec-9] com.chushiyan.test.controller.HttpHeaderController: Header 'connection' = keep-alive
2、使用MultiValueMap接收所有请求头
一个请求头存在多个值的时候,可以使用MultiValueMap接收所有请求头
1
2
3
4
5
6
7
8
|
@GetMapping ( "/getHeaders2" )
public Result multiValue( @RequestHeader MultiValueMap<String, String> headers) {
headers.forEach((key, value) -> {
logger.info(String.format(
"Header '%s' = %s" , key, value.stream().collect(Collectors.joining( "/" ))));
});
return new Result( true , HttpStatus.OK.value(), "" );
}
|
3、使用HttpHeaders接收所用请求头
1
2
3
4
5
6
7
|
@GetMapping ( "/getBaseUrl" )
public Result getBaseUrl( @RequestHeader HttpHeaders headers) {
// 获取到了所有的请求头,这里只是使用Host请求头
InetSocketAddress host = headers.getHost();
String url = "http://" + host.getHostName() + ":" + host.getPort();
return new Result( true , HttpStatus.OK.value(),url);
}
|
使用postman请求该地址,得到的响应:
1
2
3
4
5
|
{
"flag" : true ,
"code" : 200,
"message" : "http://localhost:10000"
}
|
二、@RequestHeader注解详解
@RequestHeader源码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* Annotation which indicates that a method parameter should be bound to a web request header.
*
* <p>Supported for annotated handler methods in Spring MVC and Spring WebFlux.
*
* <p>If the method parameter is {@link java.util.Map Map<String, String>},
* {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>},
* or {@link org.springframework.http.HttpHeaders HttpHeaders} then the map is
* populated with all header names and values.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
* @see RequestMapping
* @see RequestParam
* @see CookieValue
*/
@Target (ElementType.PARAMETER)
@Retention (RetentionPolicy.RUNTIME)
@Documented
public @interface RequestHeader {
/**
* Alias for {@link #name}.
*/
@AliasFor ( "name" )
String value() default "" ;
/**
* The name of the request header to bind to.
* @since 4.2
*/
@AliasFor ( "value" )
String name() default "" ;
/**
* Whether the header is required.
* <p>Defaults to {@code true}, leading to an exception being thrown
* if the header is missing in the request. Switch this to
* {@code false} if you prefer a {@code null} value if the header is
* not present in the request.
* <p>Alternatively, provide a {@link #defaultValue}, which implicitly
* sets this flag to {@code false}.
*/
boolean required() default true ;
/**
* The default value to use as a fallback.
* <p>Supplying a default value implicitly sets {@link #required} to
* {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
|
(一)name、value属性
1
2
|
public Result test( @RequestHeader (name= "accept-language" ) String language)
public Result test( @RequestHeader (value= "accept-language" ) String language)
|
上面这两行代码效果相同。当然都可以省略为:(因为value是可以省略写的)
1
|
public Result test( @RequestHeader ( "accept-language" ) String language)
|
因为从源码中,可以看出name/value互为别名:
1
2
3
4
5
|
@AliasFor ( "name" )
String value() default "" ;
@AliasFor ( "value" )
String name() default "" ;
|
@AliasFor注解:
- @AliasFor在同一个注解中成对使用,表示两个属性互为别名。比如上面的,value和name就是互为别名。
- @AliasFor标签有一些使用限制,比如要求互为别名的属性的属性值类型、默认值都是相同的。
- 互为别名的注解必须成对出现,比如value属性添加了@AliasFor(“name”),那么name属性就必须添加@AliasFor(“value”)。
(二)required属性
1
2
3
4
5
6
|
@GetMapping ( "/getHeader3" )
public Result evaluateNonRequiredHeader(
@RequestHeader (value = "chushiyan" , required = false ) String header) {
return new Result( true ,HttpStatus.OK.value(), "" );
}
|
如果没有添加required = false,当请求头中没有这个chushiyan请求头时就会报错。
(三)defaultValue属性
可以使用defaultValue属性指定默认值
1
2
3
4
5
6
|
@GetMapping ( "/getHeader3" )
public Result evaluateNonRequiredHeader(
@RequestHeader (value = "chushiyan" , defaultValue = "hello" ) String header) {
return new Result( true ,HttpStatus.OK.value(), "" );
}
|
到此这篇关于SpringBoot2中使用@RequestHeader获取请求头的方法的文章就介绍到这了,更多相关SpringBoot2 @RequestHeader获取请求头内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/chushiyan/article/details/103390406