POST request is used to create or update a resource by parameters provided in a form. In this tutorial, we will update the service created in the previous tutorial to handle the POST request. Instead of creating a html page with a form for a POST request, we use the form function provided by Jersey client library.
@POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) //@Consumes(type[, more-types]) defines which MIME type is consumed by this method public String postUser(@FormParam("id") String uid, @FormParam("name") String name) { //@FormParam for POST method acts as @PathParam for GET method if (listUsers.containsKey(uid)) { listUsers.get(uid).setName(name); return "The user is updated. Current list is: \n" + listOfUsersInText(); } listUsers.put(uid, new User(uid, name)); return "The user is added. Current list is: \n" + listOfUsersInText(); }
import javax.ws.rs.POST; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam;
package my.third.rest; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.glassfish.jersey.client.ClientConfig; public class ClientRequest { public static void main(String[] args) { String HELLO_REST_URI = "http://localhost:8080/rest"; ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(UriBuilder.fromUri(HELLO_REST_URI)).path("users"); //create a form and add to this form information of a user Form form = new Form(); form.param("id", "1"); form.param("name", "Mary"); //send this form to the server and get response Response response = target.request().accept(MediaType.TEXT_HTML) .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED)); System.out.println(response.readEntity(String.class)); } }
The user is updated. Current list is: Peter Mary
The user is added. Current list is: Mary Peter John