How To Get HTTP Request Header In Java

This example shows you how to get the HTTP request headers in Java. To get the HTTP request headers, you need this class HttpServletRequest :

1. HttpServletRequest Examples

1.1 Loop over the request header’s name and print out its value.

WebUtils.java

package com.mkyong.web.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class WebUtils {

    private Map<String, String> getHeadersInfo(HttpServletRequest request) {

        Map<String, String> map = new HashMap<String, String>();

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }

        return map;
    }

}

Request Headers example :


"headers" : {
	"Host" : "mkyong.com",
	"Accept-Encoding" : "gzip,deflate",
	"X-Forwarded-For" : "66.249.x.x",
	"X-Forwarded-Proto" : "http",
	"User-Agent" : "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
	"X-Request-Start" : "1389158003923",
	"Accept" : "*/*",
	"Connection" : "close",
	"X-Forwarded-Port" : "80",
	"From" : "googlebot(at)googlebot.com"
}

1.2 Get the “user-agent” header only.

WebUtils.java

package com.mkyong.web.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class WebUtils {

    private String getUserAgent(HttpServletRequest request) {
        return request.getHeader("user-agent");
    }

}

User agent example :


Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

2. Spring MVC Example

In Spring MVC, you can @Autowired the HttpServletRequest into any Spring managed bean directly.

SiteController.java

package com.mkyong.web.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/site")
public class SiteController {

	@Autowired
	private HttpServletRequest request;

	@RequestMapping(value = "/{input:.+}", method = RequestMethod.GET)
	public ModelAndView getDomain(@PathVariable("input") String input) {

		ModelAndView modelandView = new ModelAndView("result");

		modelandView.addObject("user-agent", getUserAgent());
		modelandView.addObject("headers", getHeadersInfo());

		return modelandView;

	}

	//get user agent
	private String getUserAgent() {
		return request.getHeader("user-agent");
	}

	//get request headers
	private Map<String, String> getHeadersInfo() {

		Map<String, String> map = new HashMap<String, String>();

		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}

		return map;
	}

}

Declare this dependency in pom.xml, if HttpServletRequest is unable to find.


	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>2.5</version>
	</dependency>

References

  1. Wikipedia – List of HTTP header fields
  2. How To Get Http Response Header In Java

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
9 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
zhoujiancyperfairymaidenLuis Lhlzbie Recent comment authors
newest oldest most voted
cyper
Guest
cyper

Spring Controller is singleton, if @autowrie request in controller, I think the injected request would be shared by all clients and leads to chaos. Isn’t it?

zhoujian
Guest
zhoujian

no it’s safe. because you get this request from ThreadLocal

fairymaiden
Guest
fairymaiden

Hi MKYong, I doubt what you said as following : “In Spring MVC, you can @Autowired the HttpServletRequest into any Spring managed bean directly. i DISAGREE this: you mean if even Spring Bean is at data layer , you still want to inject httpRequest there? is this confirmed to the Java encapsulation principle?? and best practice?, and it is secure? , so we don’t care any layer , tier or any isolation and coupling anymore? Just do what ever people want ? when Strut come out and other framework come out , it also support directly call database from web… Read more »

Latest Tutorials
Guest
Latest Tutorials

what does this mean

@RequestMapping(value = “/{input:.+}”, method = RequestMethod.GET)

why you put “:.+” i am totally confused why you use this and whts its benifit

matoelorriaga
Guest
matoelorriaga

thanks! what about the concurrent calls on the request property? will this work in the right way? thanks again!

Chrisjleu
Guest
Chrisjleu

What about cases where headers with the same name (but with different values) appear in the request? It may not be common in practice but the HTTP 1.1 specification permits it.

zbie
Guest
zbie

is is possible to get the request line using HttpServletRequest? I want to use it to distinguish the proxy request and server request. Yes I know Tomcat don’t support proxy alone, but I don’t want to install httpd or nginx on my server for some non-technical reason.

Luis Lhl
Guest
Luis Lhl

Hello Mr.Yong, I can not test this first example, when I try to execute it on my laptop it happens the following: javac HttpServletRequest.java HttpServletRequest.java:4: error: class, interface, or enum expected private HttpServletRequest request; ^ HttpServletRequest.java:7: error: class, interface, or enum expected private Map getHeadersInfo() { ^ HttpServletRequest.java:11: error: class, interface, or enum expected Enumeration headerNames = request.getHeaderNames(); ^ HttpServletRequest.java:12: error: class, interface, or enum expected while (headerNames.hasMoreElements()) { ^ HttpServletRequest.java:14: error: class, interface, or enum expected String value = request.getHeader(key); ^ HttpServletRequest.java:15: error: class, interface, or enum expected map.put(key, value); ^ HttpServletRequest.java:16: error: class, interface, or enum expected }… Read more »

fairymaiden
Guest
fairymaiden

Hi MKYong, I doubt what you said as following : “In Spring MVC, you can @Autowired the HttpServletRequest into any Spring managed bean directly. i DISAGREE this: you mean if even Spring Bean is at data layer , you still want to inject httpRequest there? is this confirmed to the Java encapsulation principle?? and best practice?, and it is secure? , so we don’t care any layer , tier or any isolation and coupling anymore? Just do what ever people want ? when Strut come out and other framework come out , it also support directly call database from web… Read more »

fairymaiden
Guest
fairymaiden

the main thing is confused me is ” any” otherwise it is good , so I dont ahree any, you like for all Spring beans include DAO beans?

fairymaiden
Guest
fairymaiden

Hi MKYong, I doubt what you said as following is right way: “In Spring MVC, you can @Autowired the HttpServletRequest into any Spring managed bean directly. and I disagree: you mean if even Spring Bean is at data layer , you still want to inject httpRequest there? is this confirmed to the Java encapsulation principle?? and best practice?, and it is secure? , so we don’t care any layer , tier or any isolation and coupling anymore? Just do what ever people want ? when Strut come out and other framework come out ,they also support directly call database from… Read more »