Creating a Java client for a form-encoded RESTful web service

Let's now create a test method for calling the previous web service that consumes form-encoded data. Open CourseManagementClient.java from the CourseManagementRESTClient project and add the following method:

  //Test addCourse method (Form-Encoded version) of CourseService 
  public static void testAddCourseForm() { 
 
    //create JAX-RS client 
    Client client = ClientBuilder.newClient(); 
 
    //Get WebTarget for a URL 
    WebTarget webTarget = 
client.target("http://localhost:8600/CourseManagementREST/services/course/add"); //Create Form object and populate fields Form form = new Form(); form.param("name", "Course-5"); form.param("credits", "5"); //Execute HTTP post method Response response = webTarget.request(). post(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED)); //check response code. 200 is OK if (response.getStatus() != 200) { //Print error message System.out.println("Error invoking REST Web Service - " +
response.getStatusInfo().getReasonPhrase() + ", Error Code : " + response.getStatus()); //Also dump content of response message System.out.println(response.readEntity(String.class)); return; } //REST call was successful. Print the response System.out.println(response.readEntity(String.class)); }

Notice that the form data is created by creating an instance of the Form object and setting its parameters. The POST request is encoded with MediaType.APPLICATION_FORM_URLENCODED, which has the following value: "application/x-www-form-urlencoded".

Now, modify the main method to call testAddCourseForm. Then, run the application by right-clicking the class and selecting Run As | Java Application. You should see the success message (from addCourseSuccess.html) printed in the console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.197