Home Tutorial Servlet Java Servlet : Http Request Headers


Share on Google+Share on Google+
Java Servlet : Http Request Headers
Posted on: October 6, 2012 at 12:00 AM
In this tutorial, you will learn how to Http Request Headers works in java servlet.

Java Servlet : Http Request Headers

In this tutorial, you will learn how to Http Request Headers works in java servlet.

Http Request Headers :

HTTP Request Header is a request line text that a HTTP client(eg. web browser)sends to a server together with other request data.
HTTP client (e.g. a browser) sends a request via GET or POST method usually. It can also send a number of headers.
Here we are mentioning some of them -

  • Accept : It indicates MIME types browser can handle. It can sends different content to different clients.
  • Accept-Charset :  It represents the character set expected to the browser.
  • Accept-Encoding : Indicates encodings (e.g., gzip or compress) browser can handle.
  • Content-Length : for POST messages, how much data is attached
  • Cookie : one of the most important headers
  • Host : This header indicates host given in orignal URL
  • User-Agent  : type of browser, useful if servlet is returning browser-specific content.

Example : In this example we are displaying  Host and User-Agent header  by passing these to the getHeader() method.


import java.io.IOException;
import java.io.PrintWriter;

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

public class HttpRequestHeaderExample extends HttpServlet {

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String host = request.getHeader("Host");
String userAgent = request.getHeader("User-Agent");
PrintWriter out = response.getWriter();
out.println("<b>Host: </b>" + host + "<br>");
out.println("<b>User Agent: </b>" + userAgent);


web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">


Output :


Related Tags for Java Servlet : Http Request Headers:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 6, 2012

Recommend the tutorial

Advertisements Advertisements