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"
}
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)!