【发布时间】:2016-07-07 01:28:31
【问题描述】:
我想发出一个HTTP POST 请求,它要求参数必须作为原始 JSON 文本传递,但我不知道如何使用 Jersey 客户端。
这是 API 规范(在 Postman Rest Client 中运行良好):(请查看我的 Postman 的屏幕截图,URL、正文中的参数和 2 个标头是 Content-Type: application/json & Accept: application/json)
以下是我对泽西岛的尝试:
JsonObject parameters = new JsonObject();
parameters.addProperty("centerId", centerId);
parameters.addProperty("studentId", studentId);
if (fromDate != null) {
parameters.addProperty("fromDate", fromDate);
}
if (toDate != null) {
parameters.addProperty("toDate", toDate);
}
Object response = client.target("http://localhost:8080/rest").path("student/calendar")
.request(MediaType.APPLICATION_JSON).post(Entity.json(parameters), String.class);
但没有任何效果。谁能建议在这种情况下处理泽西岛的正确方法是什么?谢谢。
【问题讨论】:
-
您没有使用“原始”JSON。您正在使用
JsonObject。原始 JSON 是字符串。如果您将JsonObject的字符串值传递给Entity.json,它应该可以工作。否则,您将需要一个知道如何序列化JsonObject的 Jersey 提供商。 -
实际上在
Entity.json()中我通过了parameters.toString()而不是parameter,它产生了准确的JSON 有效负载,但仍然没有工作。 -
你能粘贴你收到的异常是什么吗?我试过这个
.request(MediaType.APPLICATION_JSON).post(Entity.json(parameters.toString()), String.class);和.request(MediaType.APPLICATION_JSON).post(Entity.entity(parameters.toString(), MediaType.APPLICATION_JSON));这两个都对我有用。但是,对于以后,您需要接受它作为响应对象,然后调用response.readEntity(String.class)来获取内容。 -
这是我的有效负载字符串:
String payload = "{"schoolId":1,"studentId":1,"fromDate":"1454259600000","toDate":"1456765200000"}"。以下是我尝试使用它们时的结果:client.target("<targetURI>") .request(MediaType.APPLICATION_JSON) .post(Entity.entity(payload, MediaType.APPLICATION_JSON));--> 400 Bad Requestclient.target("<target URI>") .request(MediaType.APPLICATION_JSON) .post(Entity.json(payload), String.class);--> 400 Bad Request -
我是否需要集成 Jackson 来填充 JSON 数据?我尝试了很多次,使用了许多 API 端点,但它们总是返回 400 - Bad Request,尽管我采纳了您的建议。
标签: java json jersey http-post