Home > Software Development > How to Print out Http Request Headers in Java Servlet

How to Print out Http Request Headers in Java Servlet

August 25th, 2015 Leave a comment Go to comments

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.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

    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());
Categories: Software Development Tags: , ,
  1. December 6th, 2015 at 09:07 | #1

    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.

  1. No trackbacks yet.