JAX-RS Get HTTP Headers using @Context

In this tutorial we are going to see how to get HTTP request header using JAX-RS @Context annotation (Jersey RESTful web service)

Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Create maven web application project and add Jersey dependency in pom.xml. Find Jersey 2.x maven dependency configuration below. If you are new to maven refer our maven tutorials.

Jersey 2.x dependency in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <name>RestTutorials Maven Webapp</name>
      <!-- JAX-RS -->
        <!-- Jersey 2.19 -->


package com.ehowtonow.webservice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

public class HTTPHeaderService {

	public Response getTutorial(@Context HttpHeaders httpHeaders) {
		String userAgent = httpHeaders.getRequestHeader("user-agent").get(0);
		return Response.status(200).entity("User Agent Details : " + userAgent).build();

In this tutorials I used user-agent alone. You can access all http headers using @Context

Configure Jersey 2.x Servlet dispatcher

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

	<display-name>Restful Webservice Example</display-name>


Now you can run the service and access the service by calling the following URL


Output :

User Agent Details : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36

Ask your questions in eHowToNow Forum

To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Posts You may Like

  1. Download Text file using JAX-RS RESTful Webservice
  2. Java Data type and Identifier
  3. How to validate Email Address using Java Regular Expression
  4. Java 8 Stream Collectors groupingBy with sort Example
  5. How to format the String by using Locale
  6. How to replace the element from List
  7. Log4j Architecture
  8. JAX-RS Get HTTP Headers using @HeaderParam
  9. How to validate password using Java Regular Expression
  10. Java Best Practice – File Organization
  11. Java Mail API – Introduction
  12. How to convert List into Array
  13. JAX-RS Web service to Consume JSON using Jersey 1.x
  14. Lambda expressions are allowed only at source level 1.8 or above
  15. Java 8 Stream has already been operated upon or closed

Be the first to comment

Leave a Reply

Your email address will not be published.