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" }
To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.
Use JBoss @BadgerFish annotation that supports to return response as JSON. To return JSON as response we need to use media type as application/json.
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)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With