简体   繁体   中英

Access Request Headers in Spring Boot?

I'm using this project and specifically these 2 classes: ApplicationStartup.java and Application.java .

I googled a bit and it looks like all other examples use a specific /endpoint in order to get request headers and I just have my app running on localhost:8080 instead. But it looks like I do have /graphql endpoint so it should be possible to parse request's header.

Here are the contents of my application.yml :

server:
  port: 8080

spring:
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: false

graphql.playground:
  mapping: /playground
  endpoint: /graphql

Any Spring controller can get access to headers as part of the method arguments using @RequestHeader annotation (docs here ):

@Controller
public class MyController {
    public ResponseEntity<String> schedule(@RequestBody MyDto request,
                                           @RequestHeader HttpHeaders headers)
{
   ...
}

If you don't have access to the controller code, you can implement a OncePerRequestFilter and access the headers from the underlying servlet request using @gnana's approach.

If your question is to get the current request header then below code will do that for you.

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()) .getRequest();

request.getHeader("Authorization");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM