Get HTTP header in JAX-RS

In this tutorial, we will discuss about the two ways to get HTTP request header in JAX-RS :

  1. Inject directly with @HeaderParam
  2. Pragmatically via @Context

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("/employee")
public class EmployeeController {
 
 @GET
 @Path("/get")
 public Response addEmployee(@HeaderParam("user-agent") String userAgent) {
 
  return Response.status(200)
    .entity("addEmployee is called, userAgent : " + userAgent)
    .build();
 
 }
 
}

Access via URI pattern “http://localhost:8181/sdnext/doj/employee/get”, with Chrome, see following result :

addEmployee is called, userAgent : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36

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("/employee")
public class EmployeeController {
 
 @GET
 @Path("/get")
 public Response addEmployee(@Context HttpHeaders headers) {
 
  String userAgent = headers.getRequestHeader("user-agent").get(0);
 
  return Response.status(200)
   .entity("addEmployee is called, userAgent : " + userAgent)
   .build();
 
 }
 
}

Access via URI pattern “http://localhost:8181/sdnext/doj/employee/get”, with Chrome, see following result :

addEmployee is called, userAgent : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36

References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 

<<Previous <<   || Index ||   >>Next >>

Previous
Next