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.

Bothered by SLOW Web UI to manage vSphere? Want to manage ALL your VMware vCenters, AWS, Azure, Openstack, container behind a SINGLE pane of glass? Want to search, analyze, report, visualize VMs, hosts, networks, datastores, events as easily as Google the Web? Find out more about vSearch 3.0: the search engine for all your private and public clouds.

    StringBuffer sb = new StringBuffer();
    Enumeration<String> hns = req.getHeaderNames();
      String header = hns.nextElement();
      sb.append(header + ":");
      Enumeration<String> hvs = req.getHeaders(header);
        sb.append(hvs.nextElement() + ", ");
    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>


    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__

    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.