JAX-RS jersey Client: Reading the Response with status code

16,392

Use .get(ClientResponse.class) instead of .get(String.class). That suppresses the "exception on bad status" behavior, and the ClientResponse gives you access to details about the HTTP response. The behavior is briefly described in the user guide under "Receiving a response".

Share:
16,392
WhoAmI
Author by

WhoAmI

Playing with Play!

Updated on June 09, 2022

Comments

  • WhoAmI
    WhoAmI almost 2 years

    I am using this code for invoking a jersey JAX-RS service using a jersey client.

    public static void main(String[] args) {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
    
        WebResource service = client.resource(getBaseURI());
    
        String msg = service.path("rest").path("ExceptionDemo").path("user").queryParam("id", "001").get(String.class);     
        System.out.println(msg);
    
    }
    
    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost:8045/ExceptionHanlding").build();
    }
    

    This code works fine when the Response status code is 200. But for anything other than 200, this code throws an exception.

    How to modify this code so that based on the status code of the response it performs some action?

  • WhoAmI
    WhoAmI about 11 years
    Thanks for the reply, it resolved my problem. I can see in the link they are not using this: EntityTag e = response.getEntityTag();. What is the use of this?
  • Ryan Stewart
    Ryan Stewart about 11 years
    Put briefly, an entity tag uniquely or near-uniquely identifies a response body to enable better caching. Read more in the HTTP spec or on Wikipedia.
  • Juan Rojas
    Juan Rojas almost 4 years
    In Jersey 2 this doesn't work instead see this answer: stackoverflow.com/a/31360598/403999