Problems using @Consumes(MediaType.APPLICATION_JSON) in RESTful web service
11,120
The solution is to include in the header:
Content-Type in the header and value as application-json
Author by
John Barton
Updated on June 04, 2022Comments
-
John Barton almost 2 years
Thanks for your help. I am developing a simple RESTful webservice using JSON as a media Type. I have used successfully JSON in
GET
andDELETE
method through the use of@Produces(MediaType.APPLICATION_JSON)
. However, when I want to implementPOST
method using@Produces(MediaType.APPLICATION_JSON)
and@Consumes(MediaType.APPLICATION_JSON)
I get the next error:<h1>HTTP Status 415 - Unsupported Media Type</h1> <HR size="1" noshade="noshade"> <p> <b>type</b> Status report </p> <p> <b>message</b> <u>Unsupported Media Type</u> </p> <p> <b>description</b> <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u> </p>
My source code is the next. ALL the methods are working except the
POST
method: package RESTful.library.resources;import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import RESTful.library.service.BookService; import RESTful.library.model.Books; /** This class will implement all the request on the resource: * GET * PUT * DELETE * POST */ @Path("/books") public class BookResource { DataBaseSQLite db = new DataBaseSQLite(); BookService bookService = new BookService(); @GET @Produces(MediaType.APPLICATION_JSON) public List<Books> getBooks(){ List<Books> books = bookService.getAllBooks(); return books; } @GET @Path("/{bookID}") @Produces(MediaType.APPLICATION_JSON) public Books getBook(@PathParam("bookID") int ID){ return bookService.getBook(ID); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Books addBook(Books book) { if (book != null) return bookService.addBook(book); return null; } @DELETE @Path("/{bookID}") @Produces(MediaType.APPLICATION_JSON) public String removeBook(@PathParam("bookID") int ID){ boolean removed= bookService.deleteBook(ID); String answer="Removed successfully"; if(removed = false){ answer="Not removed"; } return answer; } @GET @Path("/name/{bookName}") @Produces(MediaType.APPLICATION_XML) public Books findBook(@PathParam("bookName") String name) { if (name != null) return bookService.findBook(name); return null; } }
I have the in pom.xml the next dependency satisfied:
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-moxy</artifactId> </dependency>
My request is sent in the next way using POSTMAN:
Do you have any idea what can be the problem? Thank you in advance.
Cheers