感谢您的帮助。我正在开发一个简单的 RESTful Web 服务,使用 JSON 作为媒体类型。我通过使用 @Produces(MediaType.APPLICATION_JSON)
在 GET
和 DELETE
方法中成功使用了 JSON。但是,当我想使用 @Produces(MediaType.APPLICATION_JSON)
和 @Consumes(MediaType.APPLICATION_JSON)
实现 POST
方法时,我得到下一个错误:
<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>
我的源代码是下一个。除 POST
方法外,所有方法均有效:
包 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;
}
}
我在 pom.xml 中满足了下一个依赖项:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
我的请求是使用 POSTMAN 以以下方式发送的:
您知道问题出在哪里吗?预先感谢您。
干杯
最佳答案
解决方案是在标题中包含:
header 中的 Content-Type 和值为 application-json
关于java - 在 RESTful Web 服务中使用 @Consumes(MediaType.APPLICATION_JSON) 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31105142/