我在论坛上查找了类似的错误,但似乎仍然无法正常工作,我得到了
Status Code: HTTP/1.1 415 Unsupported Media Type
我正在发送这个 jQuery:
$("#btnInsertCustomer").click(function (){
var myObj = {name: "Bill Adama", address:"Vancouver Canada"};
var jsondata = JSON.stringify(myObj);
$.ajax({
type: "POST",
url: "http://localhost:8081/RestDemo/services/customers/add",
contentType: "application/json",
dataType: "json",
data: jsondata,
success: function (resp, status, xhr) {
var msg = "Name: " + resp.name + ", Address: " + resp.address;
alert(msg);
$("#successPost").html(msg + " - STATUS: " + xhr.status + " " + xhr.statusText);
},
error: function(resp, status, xhr){
alert("Error: " + resp.e);
$("#errorPost").html("Error: " + resp.e + " - STATUS: " + xhr.status + " " + xhr.statusText);
}
});
});
到以下资源:
@POST
@Path("/add")
@Produces("application/json")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public String addCustomer(Customer customer) {
//insert
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
//get inserted
Customer result = customerMap.get(id);
return "{\"name\": \" " + result.getName() + " \", \"address\": \"" + result.getAddress() + "\"}";
}
它没有击中服务并给我错误。我不明白错误是在 jQuery 端(似乎没问题)还是在服务接收器中格式化发送的数据。
任何帮助表示赞赏,谢谢!
更新 1:创建了一个 DTO 来转移
$("#btnInsertCustomer").click(function (){
//var myObj = '{"name": "Bill Adama", "address":"Vancouver Canada"}';
//var jsondata = JSON.stringify(myObj);
var NewCustomer = { };
NewCustomer.name = "Bill Adama";
NewCustomer.address = "Vancouver Canada";
var DTO = { 'NewCustomer' : NewCustomer };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:8081/RestDemo/services/customers/add",
data: JSON.stringify(DTO),
dataType: "json",
success: function (resp, status, xhr) {
var msg = "Name: " + resp.name + ", Address: " + resp.address;
alert(msg);
$("#successPost").html(msg + " - STATUS: " + xhr.status + " " + xhr.statusText);
},
error: function(resp, status, xhr){
alert("Error: " + resp.e);
$("#errorPost").html(resp.e + " - STATUS: " + xhr.status + " " + xhr.statusText);
}
});
});
但我仍然得到同样的错误!