Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

jersey - How to POST a JSON object to a JAX-RS service

I am using the Jersey implementation of JAX-RS. I would like to POST a JSON object to this service but I am getting an error code 415 Unsupported Media Type. What am I missing?

Here's my code:

@Path("/orders")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class OrderResource {

    private static Map<Integer, Order> orders = new HashMap<Integer, Order>();

    @POST
    public void createOrder(Order order) {

        orders.put(order.id, order);
    }

    @GET
    @Path("/{id}")
    public Order getOrder(@PathParam("id") int id) {
        Order order = orders.get(id);
        if (order == null) {
            order = new Order(0, "Buy", "Unknown", 0);
        }
        return order;
    }
}

Here's the Order object:

public class Order {
    public int id;
    public String side;
    public String symbol;
    public int quantity;
    ...
}

A GET request like this works perfectly and returns an order in JSON format:

GET http://localhost:8080/jaxrs-oms/rest/orders/123 HTTP/1.1

However a POST request like this returns a 415:

POST http://localhost:8080/jaxrs-oms/rest/orders HTTP/1.1

{
    "id": "123",
    "symbol": "AAPL",
    "side": "Buy",
    "quantity": "1000"
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...