向WebService发出ajax请求时出现此错误:HTTP状态415-不支持的媒体类型我试图添加好的MediaType(我认为是Text / Html),但是它不起作用。我仍然有这个错误。您认为这可能是什么?谢谢 !
我的请求 :
$(document).on('submit','.form-add-edit',function(e){
e.preventDefault();
var idDisruptive = $(e.target).find('input[name=idDisruptive]').val();
var url = "api/disruptive";
var method = "POST";
if (idDisruptive){
url = url + '/' + idDisruptive;
method = "PUT";
}
$.ajax({
url: url,
method : method,
data : getDisruptiveParams(),
success : function (response){
console.log('EDIT')
console.log(response);
//editDisruptive(response);
},
error : function(response){
console.log('EDIT ERROR')
console.log(response);
}
});
});
Web服务:
@Stateless
@Path("disruptive")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_HTML, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED})
@Produces({MediaType.APPLICATION_JSON})
public class DisruptiveFacadeREST extends AbstractFacade<Disruptive> {
@PersistenceContext(unitName = "StoryGeneratorPU")
private EntityManager em;
public DisruptiveFacadeREST() {
super(Disruptive.class);
}
@POST
@Override
public void create(Disruptive entity) {
super.create(entity);
}
@PUT
@Path("{id}")
public void edit(@PathParam("id") Integer id, Disruptive entity) {
super.edit(entity);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
}
您需要在jQuery请求上设置内容类型。如果不这样做,它将默认为application/x-www-form-urlencoded
。仅仅是因为添加@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
并不意味着JAX-RS不会将表单数据转换为Disruptive
。需要有一个MessageBodyReader
来处理这种转换,而没有。同样适用MediaType.TEXT_HTML
。如果没有转换器来处理转换,那么仅添加它就没有任何意义。删除这两个。您想要的是处理JSON转换,并且MessageBodyReader
EE服务器中应该已经包含了将JSON数据转换为任意POJO的对象。
因此,对于jQuery,只需添加
$.ajax({
contentType: 'application/json'
})
那应该解决问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句