Get HTTP header in JAX-RS

In this tutorial, we show you two ways to get HTTP request header in JAX-RS :

  1. Inject directly with @HeaderParam
  2. Pragmatically via @Context
Note
Refer to this wiki page for list of the HTTP header fields.

1. @HeaderParam Example

In this example, it gets the browser “user-agent” from request header.


import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserService {

	@GET
	@Path("/get")
	public Response addUser(@HeaderParam("user-agent") String userAgent) {

		return Response.status(200)
			.entity("addUser is called, userAgent : " + userAgent)
			.build();

	}

}

Access via URI pattern “/users/get“, with FireFox, see following result :


addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0

2. @Context Example

Alternatively, you can use @Context to get “javax.ws.rs.core.HttpHeaders” directly, see equivalent version to get browser “user-agent“.


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;

@Path("/users")
public class UserService {

	@GET
	@Path("/get")
	public Response addUser(@Context HttpHeaders headers) {

		String userAgent = headers.getRequestHeader("user-agent").get(0);
		
		return Response.status(200)
			.entity("addUser is called, userAgent : " + userAgent)
			.build();

	}

}

Access via URI pattern “/users/get“, with Google Chrome, see following result :


addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 
	(KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30
List all request headers
You can list all available HTTP request headers via following code :


for(String header : headers.getRequestHeaders().keySet()){
	System.out.println(header);
}

Download Source Code

Download it – JAX-RS-Get-HTTP-Header-Example.zip (6 KB)

References

  1. JAX-RS HttpHeaders JavaDoc
  2. JAX-RS @HeaderParam JavaDoc
  3. Full list of HTTP header fields

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
12 Comment threads
3 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
14 Comment authors
Hardeek sharmaAlexgurg32Dmitry TorshinRodrigo Abreu Recent comment authors
newest oldest most voted
Alex
Guest
Alex

Great tutorial as usual. Another option is to inject the HttpServletRequest and called the getHeader(“user-agent”) method as in the following example:

public Response addUser(@Context HttpServletRequest httpServletRequest ) {
String userAgent = httpServletRequest .getHeader(“user-agent”);
// Code here
}

You can also call getHeaders() which returns an enumerator as in the example in the article. Let me suggest the blog post here https://readlearncode.com/java-ee/what-is-javax-ws-rs-core-context-httpservletresponse-and-httpservletrequest/ that also discusses the use of @Context in resource methods.

Hardeek sharma
Guest
Hardeek sharma

how can i set value converted to date type in my entity when the date in json is coming in string.
“name”: “hardeek sharma”,
“location”: “Gurgaon”,
“email”: “hardeek.sharma@gmail.com”,
“dob”: “2014/1/2”
}

Employee class

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int empId;
private String name;
private String location;
private String email;
private Date dob;

Hardeek sharma
Guest
Hardeek sharma

how can i set value converted to date type in my entity when the date in json is coming in string

Dmitry Torshin
Guest
Dmitry Torshin

Thank you! Your site is so helpful!

Rodrigo Abreu
Guest
Rodrigo Abreu

Another valid approach here would be using @Context HttpHeaders headers injected globally inside the class, so that we could benefit all methods by sharing the same instance.

pazarda domates toplayan adam
Guest
pazarda domates toplayan adam

sana puan?m 9 kanki :D

SANKALP TYAGI
Guest
SANKALP TYAGI

How can we get the http headers coming from one rest api to another

Ayemi Musa
Guest
Ayemi Musa

How can I retrieve the httpHeaders together with the request payload in the same method?

Maaz Hurzuk
Guest
Maaz Hurzuk

Were you able to get this ? Please let me know how you got it.

gurg32
Guest
gurg32

The request payload IS the main parameter of the method. What exactly are you asking here?

Nailton
Guest
Nailton

Hi, My question is how can I find out in my service the IP address and port combination the request is coming from?

venkat
Guest
venkat

If i post an xml to rest easy webservice with attributes i get the below error .Same thing works without the attribute orderid
How to reolve this? Thanks in advance 1!!

xml request -not working

FE

xml request -working

FE

Exception

[org.xml.sax.SAXParseException: The end-tag for element type "option " must end with a ‘>’ delimiter.]type Status reportmessage javax.xml.bind.UnmarshalException
– with linked exception:

Durgadas
Guest
Durgadas

Hi Mkyong,
How do we decode Basic Authentication result ?
I am using ReSTclient pluggin in firefox to fire rest calls, in that i select basic authentication and submitted the request.
How to i handle this at server side ??

Francis
Guest
Francis

@Durgadas Read the HTTPHeaders property for authorization… Should have a Basic field with a Base64 encoded string of your credentials.

Fernando França
Guest
Fernando França

Very useful. Thanks a lot!