Apart from the preceding approach, you can use a simplified version of the client API available on the Invocation.Builder object, such as head(), get(), post(), update(), put(), or delete(), to invoke the appropriate REST API. The following code snippet invokes the HTTP GET method on the department resource API in a more simplified way:
// Obtain a client reference Client client = javax.ws.rs.client.ClientBuilder.newClient(); // Bind the target to the REST service String BASE_URI = "http://localhost:8080/rest-chapter3-service/webresources"; WebTarget resource = client.target(BASE_URI).path("departments"); GenericType responseType=new GenericType<List<Department>>() { }; // Invoke GET method on the resource List<Department> depts =
resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).
get(responseType);
The following code snippet illustrates how you can invoke the PUT method on a REST resource. This example updates the Department resource and posts the modified content to the RESTful web API:
departments/{id}. } //Get the modified department object Department department = getModifiedDepartment(); String id = department.getDepartmentId(); Client client = javax.ws.rs.client.ClientBuilder.newClient(); String BASE_URI = "http://localhost:8080/rest-chapter3-service/webresources"; WebTarget resource = client.target(BASE_URI).path("departments") .path(java.text.MessageFormat.format("{0}", new Object[]{id})); Builder builder = resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON); //Invoke PUT method on resource to update the contents on server builder.put( javax.ws.rs.client.Entity.entity(department, javax.ws.rs.core.MediaType.APPLICATION_JSON));
The NetBeans IDE has good support for building the RESTful web service client by using the JAX-RS client APIs. To avail this offering, navigate to File | New | Web Services | RESTful Java Client and follow the steps in the wizard.