How to Print out Http Request Headers in Java Servlet

While developing a new project, I need to check a request header from client side AJAX call in Javascript. This is not a difficult problem at all, but I found it’s pretty helpful with the headers printed in the log file, especially while debugging. The following code snippet iterates through all the headers and add their values into the string buffer, and further into logger of the Servlet. Notice that the value of a header is not a primitive value, therefore the inner loop is needed to go over each element.

Feel free to use the following code when in need. Instead of feed the string buffer into logger, you can also send it back to the browser, which makes it more convenient to read.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

    StringBuffer sb = new StringBuffer();
    Enumeration<String> hns = req.getHeaderNames();
    while(hns.hasMoreElements())
    {
      String header = hns.nextElement();
      sb.append(header + ":");
      Enumeration<String> hvs = req.getHeaders(header);
      while(hvs.hasMoreElements())
      {
        sb.append(hvs.nextElement() + ", ");
      }
      sb.append("\n");
    }
 
    servletCtx.log("req headers:" + sb.toString());
This entry was posted in Software Development and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted December 6, 2015 at 9:07 am | Permalink

    I have almost similar site like this. I also work on software development but in this post I found very useful information which helped me to improve my knowledge about this.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.