在RESTful Web服务中使用@Consumes(MediaType.APPLICATION_JSON)的问题

时间:2015-06-28 21:52:07

标签: java json rest maven

感谢您的帮助。我正在使用JSON作为媒体类型开发一个简单的RESTful Web服务。我通过使用GETDELETE@Produces(MediaType.APPLICATION_JSON)方法中成功使用了JSON。但是,当我想使用POST@Produces(MediaType.APPLICATION_JSON)实现@Consumes(MediaType.APPLICATION_JSON)方法时,我会收到下一个错误:

<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以下一种方式发送的: POST request using JSON

你知道可能出现什么问题吗?提前谢谢。

干杯

1 个答案:

答案 0 :(得分:1)

解决方案是包含在标题中:

内容 - 在标题和值中键入application-json

Solution POST request