Java获取请求头信息的操作步骤
作者:_不吃猫的鱼_
这篇文章主要介绍了Java获取请求头信息,本文分步骤结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
Java获取请求头信息
第一步,获取request ,response
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西 HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
第二步,封装方法,获取请求头信息
private Map<String, Object> getHeads(HttpServletRequest request){ Map<String, Object> stringObjectHashMap = new HashMap<>(); Enumeration<String> headers = request.getHeaderNames(); System.out.println("请求头信息"); while(headers.hasMoreElements()){ String headName = (String)headers.nextElement(); String headValue = request.getHeader(headName); System.out.println(headName+":"+headValue); stringObjectHashMap.put(headName,headValue); } return stringObjectHashMap; }
java获取request请求头内容
注意一下request 和 httpServletRequest的类型
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while(headerNames.hasMoreElements()) {//判断是否还有下一个元素 String nextElement = headerNames.nextElement();//获取headerNames集合中的请求头 String header2 = httpServletRequest.getHeader(nextElement);//通过请求头得到请求内容 System.err.println("请求头==========key" + nextElement + "----------VALUE:" + header2); } }
到此这篇关于Java获取请求头信息的文章就介绍到这了,更多相关Java请求头信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!