Search code examples
restjerseyjax-rs

How to use @HEAD in jax-rs using Jersey API or any other jax-rs API?


How to use @HEAD in jax-rs using Jersey API or any other jax-rs API ? please give me sample.


Solution

  • Here is some dirt simple code illustrating how to send a HEAD request using the Jersey client:

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    
    WebResource resource = client
            .resource("http://localhost:8080/services/echo?message=Hello+World");
    
    ClientResponse response = resource.accept(
            MediaType.APPLICATION_JSON).head();
    System.out.println(response);
    

    Note the use of the head method. The response object returned contains lots of useful information, like the content type produced, the status code of the request, etc etc. The example can be translated to other client library types, but basically you send exactly the same request as you would with a GET, but with the HEAD method instead. Heres an example of the request that would be sent via a browser tool like 'REST Console':

    Request

    HEAD /services/echo?message=Hello+World HTTP/1.1
    Host: localhost:8080
    Connection: keep-alive
    Content-Length: 0
    Accept: application/json
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    Cookie: JSESSIONID=vWu5N2H8Y+P9SuZKWxhpIdgP.undefined
    

    Response:

    HTTP/1.1 200 OK
    Server: Apache-Coyote/1.1
    Content-Type: application/json
    Content-Length: 0
    Date: Fri, 03 May 2013 05:42:20 GMT