How to write POST method in RESTful Java using Jersey?


In our previous articles, we have seen how to write basic REST services using Jersey framework. And also we saw how to write REST client using Jersey client API. In this article we are going to see, how to write POST method and how to consume the API.


POST method is a special method and it being used interchangeably based on the situation. Meaning some will use POST method for updating an object and some people are using POST method for creating an object. It is up to the user who can decide the situation based on their need.

As you guessed so, the POST method is annotated with @POST annotation. In the below example there are 2 variables are passed from the client.
Both these parameters are annotated with @FormParam annotation.

public String createBook(@FormParam(value = "title") String title, @FormParam(value = "author") String author) {
Book book = new Book(title, author);
Gson gson = new Gson(); //Gson is used to simplify the JSON generation process
return gson.toJson(book); //Just send back the JSON to the client. But user can do anything...

Client code:

JAX-RS and Jersey have provided lot of useful API's to write REST client code.

//Setting the post method url to the client
WebTarget webTarget ="http://localhost:8080/restfullab/api").path("book");

//Add key-value pair into the form object
Form form = new Form();
form.param("title", "RESTful Java with JAX-RS 2.0 ");
form.param("author", "Bill Burke");

//Send the form object along with the post call
Response response = webTarget.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
System.out.println("Respose code: " +  response.getStatus());
System.out.println("Respose value: " + response.readEntity(String.class));

The parameters will be passed through 'Form' values as key-value pair. 'Key' should match with the @FormParam annotation value.
I hope you have enjoyed reading this post. Please give your valuable feedback or comments if you have any...

We will meet again in few days in another article. Until then enjoy hacking RESTful Java and Jersey framework! 

Source references:

Working source code is available under the following location in Github. Fork and enjoy...

Refer Jersey Javadoc for further details...