我正在使用JAX-RS的Jersey实现。我想将JSON对象发布到该服务,但收到错误代码415不支持的媒体类型。我想念什么?
这是我的代码:
@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; } }
这是Order对象:
public class Order { public int id; public String side; public String symbol; public int quantity; ... }
这样的GET请求可以完美地工作,并以JSON格式返回订单:
GET http://localhost:8080/jaxrs-oms/rest/orders/123 HTTP/1.1
但是,像这样的POST请求返回415:
POST http://localhost:8080/jaxrs-oms/rest/orders HTTP/1.1 { "id": "123", "symbol": "AAPL", "side": "Buy", "quantity": "1000" }
答案非常简单。我必须Content- Type在POST请求中添加标头,其值为application/json。没有此标头,Jersey不知道如何处理请求正文(尽管有@Consumes(MediaType.APPLICATION_JSON)注释)!
Content- Type
POST
application/json
@Consumes(MediaType.APPLICATION_JSON)