Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" } 
like image 497
Naresh Avatar asked Oct 07 '11 23:10

Naresh


People also ask

How do I post JSON to the server?

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.

How do I return a JSON response to a restful web service?

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.


1 Answers

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

like image 179
Naresh Avatar answered Sep 20 '22 14:09

Naresh