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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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:
1 2 3 4 5 6 7 8 9 10 |
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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.