首页  编辑  

SpringBoot中任意代码位置获取Header信息或者Request信息

Tags: /Java/   Date Created:
可以在Java, SpringBoot 的任意代码位置,获取到请求信息,例如下面的代码,可以获取到 Request Head信息。
如果在Controller线程外,新开线程中进行设置,例如TheadPool中调用,那么必须在 ExecutorServices.submit()的开始设置 RequestContextHolder.setRequestAttributes(),例如:
  1. ServletRequestAttributs attributes = RequestContextHolder.getRequestAttributes();
  2. executor.submit(
  3.   () -> {
  4.      RequestContextHolder.setRequestAttributes(attributes);
  5.      // ..... 做其他事情
  6. RequestContextHolder.resetRequestAttributes();
  7.   }
  8. );
否则可能报错误!

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.


  1.         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
  2.         // 获取所有的header名称和值
  3.         Enumeration<String> headerNames = request.getHeaderNames();
  4.         while (headerNames.hasMoreElements()) {
  5.             String headerName = headerNames.nextElement();
  6.             String headerValue = request.getHeader(headerName);
  7.             System.out.println("Header: " + headerName + " = " + headerValue);
  8.             // 这里可以根据需要将header信息记录到日志中或进行其他处理
  9.         }
  10.         // 你也可以获取其他请求信息,如请求路径、请求方法等等
  11.         String requestURI = request.getRequestURI();
  12.         String method = request.getMethod();
  13.         System.out.println("Request URI: " + requestURI);
  14.         System.out.println("Request Method: " + method);