REST HEAD method with Example – RESTful Web Services Tutorial

7 years ago Lalit Bhagtani 0

In REST HEAD is a method level annotation, this annotation indicates that the following method will respond to the HTTP HEAD request only. It is used to get only response status and headers information from the server but no body ( entity ). The HEAD method can be used to know, whether the resource exist on the server or not by analysing the status or header of the response for example testing validity of hyperlinks.

This method is very similar to a GET method. The meta information sent in the HTTP header of a response to a HEAD method request is identical to the meta information sent in the HTTP header of a response to a GET method request. The only difference is that response of HEAD method request does not contain message body while response of GET method request contains it.

Let’s try to understand it with an example.




REST HEAD Example :-

In this example of REST HEAD, we will hit this URL <base URL>/books/1 to get the status of the resource and HTTP header information. We will use @PathParam annotation to bind the parameter passed in this URL with the HTTP HEAD method.

import javax.ws.rs.HEAD;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class HeadMethodExample {

  @HEAD
  @Produces(MediaType.TEXT_PLAIN)
  @Path("/{id}")
  public Response getAllBooks(@PathParam("id") String bookId){
      return Response.status(201)
	 	   .entity("Book id is : " + bookId).build();
  }
	
}

Result :-

1)  HTTP Header contains the information about the resource. Status of the request is 201 ( same as api has sent ). 

REST HEAD




2) Message body is empty.

REST HEAD

References :-

  1. @HEAD Java Docs

That’s all for REST HEAD with Example. If you liked it, please share your thoughts in comments section and share it with others too.