[英]Access Request Headers in Spring Boot?
I'm using this project and specifically these 2 classes: ApplicationStartup.java and Application.java . 我正在使用这个项目 ,尤其是这两个类: ApplicationStartup.java和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. 我用谷歌搜索了一下,看起来所有其他示例都使用特定的/endpoint
来获取请求标头,而我的应用只是在localhost:8080
上运行。 But it looks like I do have /graphql
endpoint so it should be possible to parse request's header. 但是看起来我确实有/graphql
端点,因此应该可以解析请求的标头。
Here are the contents of my application.yml
: 这是我的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 ): 任何Spring控制器都可以使用@RequestHeader
批注( 此处为文档)来访问标头作为方法参数的一部分:
@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. 如果您无权访问控制器代码,则可以实现一次OncePerRequestFilter
并使用@gnana的方法访问基础servlet请求中的标头。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.