Capture HTTP Request headers using Java Servlet

HTTP header fields are components of the message header of requests and responses in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction. In this example we loop thru all Header variables and print them to screen.

The header fields are transmitted after the request or response line, the first line of a message. Header fields are colon-separated name-value pairs in clear-text string format, terminated by a carriage return (CR) and line feed (LF) character sequence. The end of the header fields is indicated by an empty field, resulting in the transmission of two consecutive CR-LF pairs.

HTTP/1.1: Header Field Definitions

HTTP Request headers using Java Servlet

Java servlet source code to display HTTP Request headers

package com.as400samplecode;

import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PrintHttpRequestHeaders extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public PrintHttpRequestHeaders() {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

        String headers = null;
        String htmlHeader = "<HTML><HEAD><TITLE> Request Headers</TITLE></HEAD><BODY>";
        String htmlFooter = "</BODY></HTML>";


        PrintWriter out = response.getWriter();
        Enumeration e = request.getHeaderNames();

        out.println("<TABLE ALIGN=CENTER BORDER=1>");
        out.println("<tr><th> Header </th><th> Value </th>");

        while (e.hasMoreElements()) {
            headers = (String) e.nextElement();
            if (headers != null) {
                out.println("<tr><td align=center><b>" + headers + "</td>");
                out.println("<td align=center>" + request.getHeader(headers)
                        + "</td></tr>");



HTTP Request headers using Java Servlet

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.