The difference between POST and PUT is: POST creates resources without defining the new resource path. Whereas, PUT creates new resources by defining complete resource path. Essentially when we are creating a new resource via PUT, we are requesting the server to create the new resource at the requested URI.
Post is submitted against resource URI like www.example.com/api/items . Please see our post example. PUT is submitted against URI like www.example.com/api/items/10 where item with id 10 is to be created as a new resource.
JAX-RS service method should be annotated with @PUT:
@Path("{sku}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response createItem(Item item, @PathParam("sku") String sku) {
if (dataService.itemExists(sku)) {
return Response.noContent()
.build();
} else {
dataService.createItem(item, sku);
//status code 201
return Response.created(uriInfo.getAbsolutePath())
.build();
}
}
Note above method contains a sub resource path via @Path("{sku}") , which is usual for a PUT method.
Here's the client code requesting a PUT:
Item item = ...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.example.com/api/customers");
String response = target.path("10")
.request()
.put(Entity.entity(item, MediaType.APPLICATION_JSON));;
Example ProjectExample ProjectDependencies and Technologies Used: - jersey-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.3.9
|