SpringBoot2中使⽤@RequestHeader获取请求头的⽅法⽬录
⼀、使⽤@RequestHeader获取请求头
(⼀)获取某⼀个请求头
(⼆)获取数值型请求头
(三)⼀次性获取所有请求头
⼆、@RequestHeader注解详解
(⼀)name、value属性
(⼆)required属性
(三)defaultValue属性
springMVC/SpringBoot中提供了@RequestHeader注解⽤来获取请求头。
⼀、使⽤@RequestHeader获取请求头
(⼀)获取某⼀个请求头
例如,获取accept-language请求头:
@GetMapping("/getLanguage")
public Result test(@RequestHeader("accept-language") String language) {
// ......
return new Result(true, 600, language);
}
使⽤postman,没有设置accept-language请求头时,响应:
{
"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请求头后,响应:
{
"flag": true,
"code": 600,
"message": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}
(⼆)获取数值型请求头
@GetMapping("/num")
public Result getNumber(@RequestHeader("my-number") int myNumber) {
return new Result(true, HttpStatus.OK.value(), String.valueOf(myNumber));
}
使⽤postman设置my-number请求头值为1,响应:
{
"flag": true,
"code": 200,
"message": "1"
}
(三)⼀次性获取所有请求头
1、使⽤Map接收所有请求头
@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] st.controller.HttpHeaderController: Header 'user-agent' = PostmanRuntime/7.20.1
2019-12-03 21:10:35,994 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'accept' = */*
2019-12-03 21:10:35,994 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'cache-control' = no-cache
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'postman-token' = 47dce6dd-c082-47b0-8867-720e45205aa1
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'host' = localhost:10000
2019-12-03 21:10:35,995 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'accept-encoding' = gzip, deflate
2019-12-03 21:10:35,996 INFO [http-nio-10000-exec-9] st.controller.HttpHeaderController: Header 'connection' = keep-alive
2、使⽤MultiValueMap接收所有请求头
⼀个请求头存在多个值的时候,可以使⽤MultiValueMap接收所有请求头
@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接收所⽤请求头
@GetMapping("/getBaseUrl")
public Result getBaseUrl(@RequestHeader HttpHeaders headers) {
// 获取到了所有的请求头,这⾥只是使⽤Host请求头
InetSocketAddress host = Host();
String url = "" + HostName() + ":" + Port();
return new Result(true, HttpStatus.OK.value(),url);
}
使⽤postman请求该地址,得到的响应:
{
"flag": true,
"code": 200,
"message": "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 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>},
php中header是什么意思* {@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)
上⾯这两⾏代码效果相同。当然都可以省略为:(因为value是可以省略写的)
public Result test(@RequestHeader("accept-language") String language)
因为从源码中,可以看出name/value互为别名:
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
@AliasFor注解:
@AliasFor在同⼀个注解中成对使⽤,表⽰两个属性互为别名。⽐如上⾯的,value和name就是互为别名。
@AliasFor标签有⼀些使⽤限制,⽐如要求互为别名的属性的属性值类型、默认值都是相同的。
互为别名的注解必须成对出现,⽐如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(),"");
}
如果没有添加required = false,当请求头中没有这个chushiyan请求头时就会报错。
(三)defaultValue属性
可以使⽤defaultValue属性指定默认值
@GetMapping("/getHeader3")
public Result evaluateNonRequiredHeader(
@RequestHeader(value = "chushiyan", defaultValue = "hello") String header) {
return new Result(true,HttpStatus.OK.value(),"");
}
到此这篇关于SpringBoot2中使⽤@RequestHeader获取请求头的⽅法的⽂章就介绍到这了,更多相关SpringBoot2 @RequestHeader获取请求头内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论