Java Code Examples for javax.servlet.http.HttpServletRequest.getHeaderNames()

The following are Jave code examples for showing how to use getHeaderNames() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hrrs   File: HrrsFilter.java   View Source Code Vote up 6 votes
private List<HttpRequestHeader> createHeaders(HttpServletRequest request) {
    List<HttpRequestHeader> headers = Collections.emptyList();
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        String value = request.getHeader(name);
        ImmutableHttpRequestHeader header = ImmutableHttpRequestHeader
                .builder()
                .setName(name)
                .setValue(value)
                .build();
        if (headers.isEmpty()) {
            headers = new ArrayList<HttpRequestHeader>();
        }
        headers.add(header);
    }
    return headers;
}
 
Example 2
Project: karate   File: SearchController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/headers", method = {GET, POST})
public Map<String, Object> echoHeaders(HttpServletRequest request) {
    Map<String, Object> map = new LinkedHashMap<>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerValues = request.getHeaders(headerName);
        List<String> list = new ArrayList();
        while (headerValues.hasMoreElements()) {
            String headerValue = headerValues.nextElement();
            list.add(headerValue);
        }
        map.put(headerName.toLowerCase(), list);
    }
    return map;
}
 
Example 3
Project: Webhook_server   File: ApiServlet.java   View Source Code Vote up 5 votes
/**
 * 获取header信息
 */
private Map<String, String> getHeadersInfo(HttpServletRequest request) {
    Map<String, String> map = new HashMap<>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    System.out.println(map);
    return map;
}
 
Example 4
Project: Spring-5.0-Cookbook   File: LoginProxyAspect.java   View Source Code Vote up 5 votes
@Before("classPointcut() && loginPointcut() && args(model,req) && @annotation(mapping)")
public String browserCheck(JoinPoint joinPoint, Model model, HttpServletRequest req, RequestMapping mapping) throws ServletException, IOException{
	
   // IP Address checking -- TO DO LIST
      // String ipAddress = req.getRemoteAddr();
   logger.info("executing " + joinPoint.getSignature().getName());
   logger.warn("MVC application trying to check browser type...");
      String loginRequestMethod = mapping.method()[0].name();
      String username = req.getParameter("username");
   String password = req.getParameter("password");
 
   req.setAttribute("username", username);
   req.setAttribute("password", password);
   
   logger.info("executing " + joinPoint.getSignature().getName() + " which is a " + loginRequestMethod + " request");
      if(loginRequestMethod.equalsIgnoreCase("GET")){
   	    Enumeration<String> headers = req.getHeaderNames();
           while(headers.hasMoreElements()){
           	String headerName = headers.nextElement(); 	
           	if(headerName.equalsIgnoreCase("user-agent")){
           	     String browserType = req.getHeader(headerName);
           	     if(browserType.contains("Chrome")){
           	    	req.setAttribute("browserNo", 1);   
           	    	logger.info("MVC application uses Chrome...");
           	     }else if (browserType.contains("Firefox")){
           	    	 req.setAttribute("browserNo", 2);
           	    	 logger.info("MVC application uses Firefox...");
           	     }else{
           	    	 req.setAttribute("browserNo", 3);
           	    	 logger.info("MVC application stops because browser not supported...");
           	     }
           	   break;
           	}
           }
      }
	return "login";
}
 
Example 5
Project: lams   File: ImplicitObjectELResolver.java   View Source Code Vote up 5 votes
/**
 *
 * Creates the Map that maps header name to single header
 * value.
 **/
public static Map<String, String> createHeaderMap (PageContext pContext)
{
  final HttpServletRequest request =
    (HttpServletRequest) pContext.getRequest ();
  return new EnumeratedMap<String, String> ()
    {
      public Enumeration<String> enumerateKeys () 
      {
        return request.getHeaderNames ();
      }

      public String getValue (Object pKey) 
      {
        if (pKey instanceof String) {
          return request.getHeader ((String) pKey);
        }
        else {
          return null;
        }
      }

      public boolean isMutable ()
      {
        return false;
      }
    };
}
 
Example 6
Project: redirector   File: AccessLoggingFilter.java   View Source Code Vote up 5 votes
private void log(HttpServletRequest request, HttpServletResponse response) {
    long duration = 0;
    try {
        final Long requestStartTime = (Long) request.getAttribute(START_TIME);
        if (requestStartTime!=null && requestStartTime > 0) {
            duration = System.currentTimeMillis() - requestStartTime;
        }
    } catch (Exception x) {
        log.warn("Could not get request start time {}", x);
    }

    final StringBuilder httpHeaders = new StringBuilder('[');
    for (final Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
        final String headerName = headerNames.nextElement();
        httpHeaders.append('[').append(headerName).append(": ").append(request.getHeader(headerName)).append("], ");
    }
    httpHeaders.append(']');

    final StringBuffer requestStringBuffer = request.getRequestURL();

    if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
        requestStringBuffer.append("?").append(request.getQueryString());
    }

    Metrics.reportGatewayRedirectDurationStats(duration);

    log.info("Request: {} {} agent={} status={} duration={} HTTP Headers={}",
            request.getMethod(), requestStringBuffer,
            request.getHeader("User-Agent"),
            response.getStatus(),
            duration != 0 ? duration : "unknown",
            httpHeaders.toString());
}
 
Example 7
Project: springboot-start   File: WebLogAspect.java   View Source Code Vote up 5 votes
private Map<String, String> getHeadersInfo(HttpServletRequest request) {
    Map<String, String> map = new HashMap<>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    return map;
}
 
Example 8
Project: xproject   File: AbstractHttpAccessLoggingInterceptor.java   View Source Code Vote up 5 votes
/**
 * 从HttpServletRequest中提取请求头信息
 * @param request
 * @param loggingContext
 * @return
 */
protected Map<String,String> extractRequestHeader(HttpServletRequest request, LoggingContext loggingContext) {
	Map<String,String> headerMap = new HashMap<String,String>();
	Enumeration<String> headerNames = request.getHeaderNames();
	if(headerNames != null){
		while(headerNames.hasMoreElements()){
			String headerName = headerNames.nextElement();
			headerMap.put(headerName, request.getHeader(headerName));
		}
	}
	return headerMap;
}
 
Example 9
Project: joai-project   File: UserInfoAction.java   View Source Code Vote up 5 votes
/**
 *  Debugging 
 *
 * @param  request  the request
 */
private void showHeaders(HttpServletRequest request) {
	prtln("\n REQUEST HEADERS");
	Enumeration headerNames = request.getHeaderNames();
	while (headerNames.hasMoreElements()) {
		String name = (String) headerNames.nextElement();
		prtln(name + ": " + request.getHeader(name));
	}
	prtln("-----------\n");
}
 
Example 10
Project: joai-project   File: SchemEditUtils.java   View Source Code Vote up 5 votes
/**
 *  Display request headers for debugging.
 *
 * @param  request  Description of the Parameter
 */
public static void showRequestHeaders(HttpServletRequest request) {
	if (debug) {
		prtln("Request Headers");
		for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
			String header = (String) e.nextElement();
			String value = request.getHeader(header);
			System.out.println("\t" + header + ": " + value);
		}
	}
}
 
Example 11
Project: joai-project   File: UcasProxyAction.java   View Source Code Vote up 5 votes
/**
 *  Debugging 
 *
 * @param  request  the request
 */
private void showHeaders(HttpServletRequest request) {
	prtln("\n REQUEST HEADERS");
	Enumeration headerNames = request.getHeaderNames();
	while (headerNames.hasMoreElements()) {
		String name = (String) headerNames.nextElement();
		prtln(name + ": " + request.getHeader(name));
	}
	prtln("-----------\n");
}
 
Example 12
Project: istio-ola   File: OlaController.java   View Source Code Vote up 5 votes
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/ola", produces = "text/plain")
@ApiOperation("Returns the greeting in Portuguese")
public String ola(HttpServletRequest request) {
  String hostname = System.getenv().getOrDefault("HOSTNAME", "Unknown");
  Enumeration<String> headerNames = request.getHeaderNames();

  StringBuffer headerMsg = new StringBuffer("{");

  while (headerNames.hasMoreElements()) {
    String headerName = headerNames.nextElement();
    String headerValue = request.getHeader(headerName);
    if (headerValue != null) {
      headerMsg.append(String.format("{\"%s\":\"%s\"}", headerName, headerValue));
      headerMsg.append(",");
    }
  }

  headerMsg.append("}");

  log.info("Request Headers:{}", headerMsg);
  return String.format("Olá de %s", hostname);
}
 
Example 13
Project: ja-micro   File: RpcHandler.java   View Source Code Vote up 5 votes
protected Map<String, String> gatherHttpHeaders(HttpServletRequest req) {
    Map<String, String> headers = new HashMap<>();

    Enumeration<String> headerNames = req.getHeaderNames();
    if (headerNames == null) {
        return headers;
    }

    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headerValues = req.getHeaders(headerName);
        if (headerValues == null) {
            continue;
        }

        String headerNameLower = headerName.toLowerCase();
        if (! blackListedHeaders.contains(headerNameLower)) {
            if (headerValues.hasMoreElements()) {
                headers.put(headerNameLower, headerValues.nextElement());
            }

            while (headerValues.hasMoreElements()) {
                logger.debug("Duplicate http-header, discarding: {} = {}", headerName, headerValues.nextElement());
            }
        } else {
            logger.trace("Blocking header {}", headerNameLower);
        }
    }

    return headers;
}
 
Example 14
Project: tangyuan2   File: ServletUtils.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static void printHttpHeader(HttpServletRequest request) {
	Enumeration<String> headerNames = request.getHeaderNames();
	while (headerNames.hasMoreElements()) {
		String key = (String) headerNames.nextElement();
		String value = request.getHeader(key);
		log.debug(key + ":" + value);
	}
}
 
Example 15
Project: lams   File: ImplicitObjectELResolver.java   View Source Code Vote up 5 votes
/**
 *
 * Creates the Map that maps header name to an array of header
 * values.
 **/
public static Map<String, String[]> createHeadersMap (PageContext pContext)
{
  final HttpServletRequest request =
    (HttpServletRequest) pContext.getRequest ();
  return new EnumeratedMap<String, String[]> ()
    {
      public Enumeration<String> enumerateKeys () 
      {
        return request.getHeaderNames ();
      }

      public String[] getValue (Object pKey) 
      {
        if (pKey instanceof String) {
          // Drain the header enumeration
          List<String> l = new ArrayList<String> ();
          Enumeration<String> e = request.getHeaders ((String) pKey);
          if (e != null) {
            while (e.hasMoreElements ()) {
              l.add (e.nextElement ());
            }
          }
          return l.toArray (new String [l.size ()]);
        }
        else {
          return null;
        }
      }

      public boolean isMutable ()
      {
        return false;
      }
    };
}
 
Example 16
Project: monarch   File: LoginHandlerInterceptor.java   View Source Code Vote up 4 votes
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
    final Object handler) throws Exception {
  final Map<String, String> requestParameterValues = new HashMap<String, String>();

  for (Enumeration<String> requestParameters = request.getParameterNames(); requestParameters
      .hasMoreElements();) {
    final String requestParameter = requestParameters.nextElement();
    if (requestParameter.startsWith(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX)) {
      String requestValue = request.getParameter(requestParameter);
      // GEODE-1469: since we enced stepArgs, we will need to decode it here. See
      // #ClientHttpRequest
      if (requestParameter.contains(CLIMultiStepHelper.STEP_ARGS)) {
        requestValue = UriUtils.decode(requestValue);
      }
      requestParameterValues.put(
          requestParameter.substring(ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX.length()),
          requestValue);
    }
  }



  for (Enumeration<String> requestHeaders = request.getHeaderNames(); requestHeaders
      .hasMoreElements();) {

    // since http request headers are case-insensitive and all our security-* properties
    // are in lower case, it's safe to do toLowerCase here.
    final String requestHeader = requestHeaders.nextElement().toLowerCase();

    if (requestHeader.startsWith(SECURITY_VARIABLE_REQUEST_HEADER_PREFIX)) {
      requestParameterValues.put(requestHeader, request.getHeader(requestHeader));
    }
  }

  String username = requestParameterValues.get(ResourceConstants.USER_NAME);
  String password = requestParameterValues.get(ResourceConstants.PASSWORD);
  this.securityService.login(username, password);

  ENV.set(requestParameterValues);

  return true;
}
 
Example 17
Project: AppServiceRestFul   File: RestFulInterceptor.java   View Source Code Vote up 4 votes
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
	// TODO Auto-generated method stub
	
	String uri = request.getRequestURI();
	Map<String, String> headerMaps = new HashMap<String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        headerMaps.put(key, value);
    }
    if(!uri.endsWith(".do"))
    {
    	return true;
    }
    if(uri.endsWith("user/loginbypwd.do"))//登录
	{
		return true;
		
	}
	else if(uri.endsWith("user/register.do"))//注册
	{
		return true;
	}
	else if(uri.endsWith("pay/verifyalipayresult.do"))//支付宝回调接口
	{
		return true;
	}
	else if(uri.endsWith("pay/verifywxpayresult.do"))//微信回调接口
	{
		return true;
	}
	else if(uri.endsWith("update/checkupdate.do"))//检查更新
	{
		return true;
	}
	else
	{
		TokenBean tokenBean = tokenDao.isTokenAvailable(headerMaps.get("phone"));
		if(tokenBean != null && tokenBean.getToken().equals(headerMaps.get("token")))
		{
			return true;
		}
		else
		{
			RestFulBean<TokenBean> resuFulBean = RestFulUtil.getInstance().getResuFulBean(null, 1, "用户身份验证失败");
			response.setContentType("application/json;charset=UTF-8");
			Writer writer = response.getWriter();
			writer.write(JSONObject.toJSONString(resuFulBean, SerializerFeature.WriteMapNullValue));
			return false;
		}
	}
}
 
Example 18
Project: AppServiceRestFul   File: RestFulInterceptor.java   View Source Code Vote up 4 votes
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
	// TODO Auto-generated method stub
	
	String uri = request.getRequestURI();
	Map<String, String> headerMaps = new HashMap<String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        headerMaps.put(key, value);
    }
    if(!uri.endsWith(".do"))
    {
    	return true;
    }
    if(uri.endsWith("user/loginbypwd.do"))//登录
	{
		return true;
		
	}
	else if(uri.endsWith("user/register.do"))//注册
	{
		return true;
	}
	else if(uri.endsWith("pay/verifyalipayresult.do"))//支付宝回调接口
	{
		return true;
	}
	else
	{
		TokenBean tokenBean = tokenDao.isTokenAvailable(headerMaps.get("phone"));
		if(tokenBean != null && tokenBean.getToken().equals(headerMaps.get("token")))
		{
			return true;
		}
		else
		{
			RestFulBean<TokenBean> resuFulBean = RestFulUtil.getInstance().getResuFulBean(null, 1, "用户身份验证失败");
			response.setContentType("application/json;charset=UTF-8");
			Writer writer = response.getWriter();
			writer.write(JSONObject.toJSONString(resuFulBean, SerializerFeature.WriteMapNullValue));
			return false;
		}
	}
}
 
Example 19
Project: gitplex-mit   File: ServletRequestCopy.java   View Source Code Vote up 4 votes
public ServletRequestCopy(HttpServletRequest request) {
	this.servletPath = request.getServletPath();
	this.contextPath = request.getContextPath();
	this.pathInfo = request.getPathInfo();
	this.requestUri = request.getRequestURI();
	this.requestURL = request.getRequestURL();
	this.method = request.getMethod();
	this.serverName = request.getServerName();
	this.serverPort = request.getServerPort();
	this.protocol = request.getProtocol();
	this.scheme = request.getScheme();
	
	
	/*
	 * have to comment out below two lines as otherwise web socket will
	 * report UnSupportedOperationException upon connection
	 */
	//this.characterEncoding = request.getCharacterEncoding();
	//this.contentType = request.getContentType();
	//this.requestedSessionId = request.getRequestedSessionId();
	this.characterEncoding = null;
	this.contentType = null;
	this.requestedSessionId = null;
	
	this.locale = request.getLocale();
	this.locales = request.getLocales();
	this.isSecure = request.isSecure();
	this.remoteUser = request.getRemoteUser();
	this.remoteAddr = request.getRemoteAddr();
	this.remoteHost = request.getRemoteHost();
	this.remotePort = request.getRemotePort();
	this.localAddr = request.getLocalAddr();
	this.localName = request.getLocalName();
	this.localPort = request.getLocalPort();
	this.pathTranslated = request.getPathTranslated();
	this.principal = request.getUserPrincipal();

	HttpSession session = request.getSession(true);
	httpSession = new HttpSessionCopy(session);

	String s;
	Enumeration<String> e = request.getHeaderNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		Enumeration<String> headerValues = request.getHeaders(s);
		this.headers.put(s, headerValues);
	}

	e = request.getAttributeNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		attributes.put(s, request.getAttribute(s));
	}

	e = request.getParameterNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		parameters.put(s, request.getParameterValues(s));
	}
}
 
Example 20
Project: apache-tomcat-7.0.73-with-comment   File: RequestHeaderExample.java   View Source Code Vote up 4 votes
@Override
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException
{
    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");

    String title = RB.getString("requestheader.title");
    out.println("<title>" + title + "</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");

    // all links relative

    // XXX
    // making these absolute till we work out the
    // addition of a PathInfo issue

    out.println("<a href=\"../reqheaders.html\">");
    out.println("<img src=\"../images/code.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"view code\"></a>");
    out.println("<a href=\"../index.html\">");
    out.println("<img src=\"../images/return.gif\" height=24 " +
                "width=24 align=right border=0 alt=\"return\"></a>");

    out.println("<h3>" + title + "</h3>");
    out.println("<table border=0>");
    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
        String headerName = e.nextElement();
        String headerValue = request.getHeader(headerName);
        out.println("<tr><td bgcolor=\"#CCCCCC\">");
        out.println(HTMLFilter.filter(headerName));
        out.println("</td><td>");
        if (headerName.toLowerCase(Locale.ENGLISH).contains("cookie")) {
            HttpSession session = request.getSession(false);
            String sessionId = null;
            if (session != null) {
                sessionId = session.getId();
            }
            out.println(HTMLFilter.filter(CookieFilter.filter(headerValue, sessionId)));
        } else {
            out.println(HTMLFilter.filter(headerValue));
        }
        out.println("</td></tr>");
    }
    out.println("</table>");
}