我有以下 Angular 代码:
<button ng-click="ctrl.submit(light)">Switch</button>
按钮点击由以下方式处理:
self.submit = function(light) {
console.log("==============================");
console.log("clicked button: ", light);
console.log("==============================");
$http.post('/ARHomeAutomation/rest/light/state/', light).then(function(response) {
console.log('headers: ' , response.headers);
console.log('status: ', response.status);
console.log('config: ', response.config);
console.log('data: ', response.data);
self.state = response.data;
}, function(errResponse) {
console.error('Error while updating light state');
})
console.log('User clicked submit with: ', light.id );
console.log('response: ', self.light);
}
在服务器端,我有以下方法应该响应请求:
@POST
@Path("/state/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_HTML)
public String setStateOfLight(JSONObject aLight) {
if(aLight == null) {
return "It's a null";
} else {
System.out.println("content: " + aLight);
}
JSONObject jsonObject = new JSONObject();
//Update the state of the light with the given id
for(Light light: lightCollection) {
// .....
}
return getLightsStateAsJSON();
}
当我单击按钮时,我收到以下消息:
根据 Firefox,我确实在请求中发送了 JSON。至少当我检查发送数据时是这样说的。
这是我的 header 请求数据:
我在这里缺少什么?
最佳答案
"I downloaded Jersey 2.17 with all dependencies. AT least that what it says on their download site"
是的,是的the Jersey distribution (Jersey JAX-RS 2.0 RI bundle )除了可以从 InputStream
转换的基本低级类型之外,不捆绑 JSON 转换支持。因此,除了 Jersey Bundle 中的 jar 之外,您可以使用的唯一类型是 String
、InputStream
和 byte[]
。如果您尝试操作 JSON,并没有多大帮助
转换的工作原理是通过使用MessageBodyReader
和MessageBodyWriter
。我不知道 JSONObject
是什么,但我猜它来自 here 。无论如何,您都需要一个 MessageBodyReader
来处理传入的转换。我猜你没有。我个人不知道从哪里可以获得该特定 API。
我会使用一个可以处理 JSON 到 POJO 映射的库。 jackson 是我推荐的人之一。基本的内容非常容易理解。假设这是您的 JSON
{"name":"your name", "id": "2"}
您需要做的就是使用 JavaBean naming convention 创建一个包含字段和属性的类。 。所以对于上面的 JSON,我们可以使用这个
public class User {
private String name;
private String id;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
}
现在您的方法参数可以接受 User
类型。
要获得此支持,您需要添加 Jackson 提供程序。下载以下内容
获取下图中的所有内容
我有一张来自另一篇文章的 v2.2.3 图像 - 忽略版本。您希望为所有这些版本获得 2.3.2。对于第一个依赖项,它们都可以在上面的链接中找到。只需在搜索栏中搜索它们即可。找到它后,选择版本并下载。
添加这些 jar 后。你应该有 JSON 到 POJO 支持。
关于java - 向服务器发送 JSON 会给出 415 不支持的媒体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788461/