How to write REST service client with JAX-RS API?


The purpose of the article is how to write REST service client code JAX-RS api. I hope you have understood the basic concepts of RESTful web services and how to write services with Jersey framework. Now we will write some code to consume the REST service using the JAX-RS client API.

Possible ways of REST client:

There are many possible ways through which we can communicate with the available rest services. Here our main focus is to communicate with rest services using JAX-RS code. The other possible ways are the following,

  • CURL
  • Advanced REST client (browser plugin)
  • Post Man (browser plugin)
In one of the previous example, I have explained how to write rest services. Based on the above article I assume, there is a service running in Tomcat in the following url,
And we have defined one resource with GET method in "hello"

So the complete url to access the rest end-point is http://localhost:8080/restfullab/api/hello

Client code:

Client client = ClientBuilder.newClient();
WebTarget webTarget ="http://localhost:8080/restfullab/api").path("hello");

Response response = webTarget.request(MediaType.TEXT_PLAIN).get();
System.out.println(response.getStatus()); //Prints the response code. 200 if OK
System.out.println(response.readEntity(String.class)); // Prints the response text

I hope this article have given an overview on how to call REST service using JAX-RS api. In the next article we will see how to call other types of methods like POST, PUT and DELETE.