Monday, November 24, 2014

REST service client with JAX-RS API

Background:

Are you still using Apache HTTP client or Java URL connection to speak with REST service? Then this article is for you. JAX-RS specification has released with new client API to communicate with RESTful services. Here you can see how you can use JAX-RS client API for your communication.

As a first step, we have to create a web target in-order to talk to our web services. Using the ClientBuilder, we should create a Client object.

From the client object we can create WebTarget object like below,

WebTarget api will accept base path and resource path separately. But we can also give the combined url as a whole to the target method.

Once we get the webTarget object, we are ready to communicate with the REST service. From the webTarget object we can invoke the respective REST methods...

In the above image we have called the get method. This will return the response object. From the response object we can validate the response status and read the entity from the response.

Just to get the JSON string from the response, we have passed the object type (String.class) to the readEntity method. If we get any complex object type, we can still use them.

I hope you will enjoy this article. Please give your comments or feedback if you have any... We will meet shortly with another article.

No comments:

Post a Comment