POST request is meant to update an existing resource or to create a new resource. In both cases the request URI typically points to the resource collection, for example http://www.example.com/api/customers (for creating/updating a customer or multiple customers).
Client includes the data to be updated in the the message body and content information in the header. Content information (also known as content negotiation) describes what type of data is in the body and also what type of data client accepts in the response.
JAX-RS service method should be annotated with @POST:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String createCustomer(Customer customer) {
...
}
Above method consumes JSON data only. A method can consumer multiple data type as well. For example:
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces(MediaType.TEXT_PLAIN)
public String createCustomer(Customer customer) {
... ...
}
If our Customer object is annotated with JAXB annotations, then we don't have to do any special handling to distinguish the two as the data conversion is automatically done by the registered MessageBodyWriter/MessageBodyReader provider.
As we saw in media type restriction tutorial, the second last method is uniquely defined for a post request accepting only JSON data. We can define more post methods with same URI path and with HTTP method but consuming different data types.
For a successful request, client needs to provide the content type of the message body in the request header and at the same time it needs to specify what media type it's accepting in response. JAX-RS client code typically looks like this:
Customer newCustomer = ...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.example.com/api/customers");
String response = target.request(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_PLAIN_TYPE)
.post(Entity.json(newCustomer), String.class);
Example ProjectDependencies and Technologies Used: - jersey-core-server 2.22.1: Jersey core server implementation.
- jersey-container-servlet 2.22.1: Jersey core Servlet 3.x implementation.
- jersey-media-moxy 2.22.1:
Jersey JSON entity providers support module based on EclipseLink MOXy.
- jersey-test-framework-provider-jdk-http 2.22.1: Jersey Test Framework - JDK HTTP container.
- JDK 1.8
- Maven 3.0.4
|