SpringMVC/SpringBoot2中使用@RequestHeader獲取請(qǐng)求頭
springMVC/SpringBoot中提供了@RequestHeader注解用來(lái)獲取請(qǐng)求頭。
一、使用@RequestHeader獲取請(qǐng)求頭
(一)獲取某一個(gè)請(qǐng)求頭
例如谱煤,獲取accept-language請(qǐng)求頭:
@GetMapping("/getLanguage")
public Result test(@RequestHeader("accept-language") String language) {
// ......
return new Result(true, 600, language);
}
使用postman,沒(méi)有設(shè)置accept-language請(qǐng)求頭時(shí)倦踢,響應(yīng):
{
"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請(qǐng)求頭后均唉,響應(yīng):
{
"flag": true,
"code": 600,
"message": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}
(二)獲取數(shù)值型請(qǐng)求頭
@GetMapping("/num")
public Result getNumber(@RequestHeader("my-number") int myNumber) {
return new Result(true, HttpStatus.OK.value(), String.valueOf(myNumber));
}
使用postman設(shè)置my-number請(qǐng)求頭值為1寸谜,響應(yīng):
{
"flag": true,
"code": 200,
"message": "1"
}
(三)一次性獲取所有請(qǐng)求頭
1癌淮、使用Map接收所有請(qǐng)求頭
@GetMapping("/getHeaders")
public Result listAllHeaders(@RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> {
// 日志中輸出所有請(qǐng)求頭
logger.info(String.format("Header '%s' = %s", key, value));
});
return new Result(true, HttpStatus.OK.value(), "");
}
使用postman請(qǐng)求該地址躺坟,控制臺(tái)打印:
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接收所有請(qǐng)求頭
一個(gè)請(qǐng)求頭存在多個(gè)值的時(shí)候咪橙,可以使用MultiValueMap接收所有請(qǐng)求頭
@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接收所用請(qǐng)求頭
@GetMapping("/getBaseUrl")
public Result getBaseUrl(@RequestHeader HttpHeaders headers) {
// 獲取到了所有的請(qǐng)求頭虚倒,這里只是使用Host請(qǐng)求頭
InetSocketAddress host = headers.getHost();
String url = "http://" + host.getHostName() + ":" + host.getPort();
return new Result(true, HttpStatus.OK.value(),url);
}
使用postman請(qǐng)求該地址美侦,得到的響應(yīng):
{
"flag": true,
"code": 200,
"message": "http://localhost:10000"
}
二、@RequestHeader注解詳解
@RequestHeader源碼如下:
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屬性
public Result test(@RequestHeader(name="accept-language") String language)
public Result test(@RequestHeader(value="accept-language") String language)
上面這兩行代碼效果相同菠剩。當(dāng)然都可以省略為:(因?yàn)関alue是可以省略寫的)
public Result test(@RequestHeader("accept-language") String language)
因?yàn)閺脑创a中,可以看出name/value互為別名:
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
@AliasFor注解:
- @AliasFor在同一個(gè)注解中成對(duì)使用耻煤,表示兩個(gè)屬性互為別名具壮。比如上面的,value和name就是互為別名哈蝇。
- @AliasFor標(biāo)簽有一些使用限制嘴办,比如要求互為別名的屬性的屬性值類型、默認(rèn)值都是相同的买鸽。
- 互為別名的注解必須成對(duì)出現(xiàn),比如value屬性添加了@AliasFor(“name”)贯被,那么name屬性就必須添加@AliasFor(“value”)眼五。
(二)required屬性
@GetMapping("/getHeader3")
public Result evaluateNonRequiredHeader(
@RequestHeader(value = "chushiyan", required = false) String header) {
return new Result(true,HttpStatus.OK.value(),"");
}
如果沒(méi)有添加required = false妆艘,當(dāng)請(qǐng)求頭中沒(méi)有這個(gè)chushiyan請(qǐng)求頭時(shí)就會(huì)報(bào)錯(cuò)。
(三)defaultValue屬性
可以使用defaultValue屬性指定默認(rèn)值
@GetMapping("/getHeader3")
public Result evaluateNonRequiredHeader(
@RequestHeader(value = "chushiyan", defaultValue = "hello") String header) {
return new Result(true,HttpStatus.OK.value(),"");
}