Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 377
WhoAmI Avatar asked Mar 03 '13 13:03

WhoAmI


People also ask

What is Jax-RS and Jersey?

The JAX-RS (JSR 311: The Java API for RESTful Web Services) specification provides a standardized Java-based approach to implementing REST-style web services. Jersey is the reference implementation of JAX-RS and I provide a brief introduction to JAX-RS via Jersey in this blog post.

What is jersey client used for?

Jersey is an open source framework for developing RESTFul Web Services. It also has great inbuilt client capabilities.

How do you return a response in Java?

The Response class is an abstract class that contains three simple methods. The getEntity() method returns the Java object you want converted into an HTTP message body. The getStatus() method returns the HTTP response code. The getMetadata() method is a MultivaluedMap of response headers.

Why is Jersey framework used?

Jersey is Sun's production quality reference implementation for JSR 311: JAX-RS: The Java API for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful web services with Java and the Java JVM.


1 Answers

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".

like image 179
Ryan Stewart Avatar answered Sep 17 '22 21:09

Ryan Stewart