如何将 JSON 对象发布到 JAX-RS 服务如何将、对象、RS、JSON

2023-09-06 10:51:03 作者:符咒 The devil◢

我正在使用 JAX-RS 的 Jersey 实现.我想向此服务发布一个 JSON 对象,但我收到错误代码 415 Unsupported Media Type.我错过了什么?

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?

这是我的代码:

@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 对象:

Here's the Order object:

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

这样的 GET 请求完美运行,并返回 JSON 格式的订单:

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

但是像这样的 POST 请求会返回 415:

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

推荐答案

答案出奇的简单.我必须在 POST 请求中添加一个 Content-Type 标头,其值为 application/json.如果没有此标头,Jersey 不知道如何处理请求正文(尽管有 @Consumes(MediaType.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)!