Share on Google+Share on Google+

Java Servlet : Http Request Headers

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 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="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">


Output :



Posted on: October 6, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null