亲宝软件园·资讯

展开

SpringBoot2 @RequestHeader获取请求头

chushiyan 人气:0

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] 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接收所有请求头

@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 = headers.getHost();
    String url = "http://" + host.getHostName() + ":" + host.getPort();
    return new Result(true, HttpStatus.OK.value(),url);
}

使用postman请求该地址,得到的响应:

{
    "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&lt;String, String&gt;},
 * {@link org.springframework.util.MultiValueMap MultiValueMap&lt;String, String&gt;},
 * 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注解:

(二)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(),"");
}

加载全部内容

相关教程
猜你喜欢
用户评论