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?
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.
Jersey is an open source framework for developing RESTFul Web Services. It also has great inbuilt client capabilities.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With