JAX-RS @HeaderParam with Example – RESTful Web Services Tutorial

7 years ago Lalit Bhagtani 0

In JAX-RS @HeaderParam annotation is used to bind HTTP request header values to the method arguments. 

Let’s try to understand it with an example.

Example 1 :-

In this example of JAX-RS @HeaderParam, we will hit this URL <base URL>/books/chapters to print values of  “User-Agent” and “Accept-Language” parameter from the request header.

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

@Path("books")
public class HeaderParamExample {

   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/chapters")
   public Response getListOfBooks(@HeaderParam("Accept-Language") String acceptLanguage,
			@HeaderParam("User-Agent") String userAgent){
       return Response.status(200)
	              .entity("User-Agent :- " + userAgent + " \nAccept-Language :- " + acceptLanguage)
                      .build();
   }
	
}



Result :-

JAX-RS @HeaderParam

Example 2 :-

In this example, we will use @Context annotation and HttpHeaders object to get HTTP request header values in the method arguments.

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

@Path("books")
public class HeaderParamExample {

   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/chapters")
   public Response getListOfBooks(@Context HttpHeaders httpHeaders){
 	String userAgent = httpHeaders.getRequestHeader("User-Agent").get(0);
	String contentType = httpHeaders.getRequestHeader("Content-Type").get(0);
	return Response.status(200)
		       .entity("User-Agent :- " + userAgent + " \nContent-Type :- " + contentType)
		       .build();
   }
	
}



Result :-

JAX-RS @HeaderParam

References :-

  1. @HeaderParam Java Docs
  2. @Context Java Docs
  3. @HttpHeaders Java Docs

That’s all for JAX-RS @HeaderParam with Example. If you liked it, please share your thoughts in comments section and share it with others too.