Let's now create a Java client application that calls the previous web service. Create a simple Maven project and call it CourseManagementRESTClient:
Figure 9.3: Create a JAX-RS client project
Open pom.xml and add a dependency for the Jersey client module:
<dependencies> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.18</version> </dependency> </dependencies>
Create a Java class called CourseManagementRESTClient in the packt.jee.eclipse.rest.ws.client package:
Figure 9.4: Create a REST client main class
You could invoke a RESTful web service using java.net.HttpURLConnection or other external HTTP client libraries. But JAX-RS client APIs make this task a lot easier, as you can see in the following code:
package packt.jee.eclipse.rest.ws.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * This is a simple test class for invoking RESTful web service * using JAX-RS client APIs */ public class CourseManagementClient { public static void main(String[] args) { testGetCoursesJSON(); } //Test getCourse method (XML or JSON) of CourseService public static void testGetCoursesJSON() { //Create JAX-RS client Client client = ClientBuilder.newClient(); //Get WebTarget for a URL WebTarget webTarget =
client.target("http://localhost:8080/CourseManagementREST/services/course"); //Add paths to URL webTarget = webTarget.path("get").path("10"); //We could also have create webTarget in one call with the full URL - //WebTarget webTarget =
client.target("http://localhost:8080/CourseManagementREST/services/course/get/10"); //Execute HTTP get method Response response =
webTarget.request(MediaType.APPLICATION_JSON).get(); //Check response code. 200 is OK if (response.getStatus() != 200) { System.out.println("Error invoking REST web service - " +
response.getStatusInfo().getReasonPhrase()); return; } //REST call was successful. Print the response System.out.println(response.readEntity(String.class)); } }
For a detailed description of how to use the JAX-RS client APIs, refer to https://jersey.java.net/documentation/latest/client.html.