[英]Unsupported Media Type with Java POST request
I have a java class: 我有一个Java类:
@XmlRootElement
public class RoomInfo {
@XmlElement
public String name;
@XmlElement
public String w;
@XmlElement
public String h;
@XmlElement
public String size;
}
And a restful web service: 宁静的Web服务:
@Path("/create")
public class Create {
@POST
@Consumes("application/json")
public void getInfo(RoomInfo room){
System.out.println("signal");
System.out.println(room.name);
System.out.println(room.w);
System.out.println(room.h);
System.out.println(room.size);
}
}
I am trying to send a POST request with json parameters with javascript: 我正在尝试使用javascript发送带有json参数的POST请求:
var xh = new XMLHttpRequest();
var json = JSON.stringify({
name: "Room1",
w: "2",
h: "4",
size: "12"
});
xh.open("POST", 'http://localhost:8080/create', true);
xh.setRequestHeader('Content-type', 'application/json; charset=utf-8');
console.log(json);
xh.send(json);
But I get the following output in the console of my browser: 但是我在浏览器的控制台中得到以下输出:
{"name":"Room1","w":"2","h":"4","size":"12"} {“ name”:“ Room1”,“ w”:“ 2”,“ h”:“ 4”,“ size”:“ 12”}
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) 加载资源失败:服务器响应状态为415(不支持的媒体类型)
I understand that for some reason the data I send cannot be put into my RoomInfo object but I don't understand why. 我了解由于某种原因,我发送的数据无法放入RoomInfo对象,但我不明白为什么。
The server console also shows the following: com.sun.jersey.spi.container.ContainerRequest.getEntity A message body reader for Java class com.example.jersey.RoomInfo, and Java type class com.example.jersey.RoomInfo, and MIME media type application/json; 服务器控制台还显示以下内容:com.sun.jersey.spi.container.ContainerRequest.getEntity Java类com.example.jersey.RoomInfo和Java类型类com.example.jersey.RoomInfo和MIME的消息正文阅读器媒体类型application / json; charset=UTF-8 was not found. 找不到字符集= UTF-8。 The registered message body readers compatible with the MIME media type are: application/json; 与MIME媒体类型兼容的已注册消息正文阅读器为:application / json; charset=UTF-8 -> charset = UTF-8->
For the POST to work correctly your POST needs to set a 'Content-Type' header of 'application/json' 为了使POST正常工作,您的POST需要设置“ application / json”的“ Content-Type”标头
Then your POST method may also need @Produces(MediaType.APPLICATION_JSON) 然后,您的POST方法可能还需要@Produces(MediaType.APPLICATION_JSON)
Also the POJO does need a default constructor as mentioned above. 同样,POJO确实需要如上所述的默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.