How to get HTTP Request Header In Java

In this post , we will see how to get HTTP request header in java. Sometimes, you want to print request header values.
It is very simple to do it. You first need to get request object, then call getHeaderFields()  on it to get all request header values.

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
...
        // Get header object
 private HttpServletRequest request;
... 
 public Map getRequestHeaderValues()
 {

  Map map = new HashMap();
                // get header values from request object
  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
   String key = (String) headerNames.nextElement();
   String value = request.getHeader(key);
   map.put(key, value);
  }

  return map;
 }

}

Spring MVC:

If you are using Spring MVC, then you can use @Autowired annotation to get request object in controller.

import javax.servlet.http.HttpServletRequest;

import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author java2blog.com
 * 
 */
@RestController
public class CountryController {

 @Autowired
 private HttpServletRequest request;
 CountryService countryService = new CountryService();

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List getCountries() {

  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
   String key = (String) headerNames.nextElement();
   String value = request.getHeader(key);
   System.out.println(key+" : "+value);
  }
  List listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }
}

You will get output as below:

host : localhost:8080
accept : text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
connection : keep-alive
cookie : JSESSIONID=822C2725DB96155EF6B37CC2A1F5E2A4
user-agent : Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.78.2 (KHTML, like Gecko) Safari/522.0
accept-language : en-us
cache-control : no-cache
accept-encoding : gzip, deflate
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.