JAX-RS:HTTP状态415 - 不支持的媒体类型

时间:2018-03-18 15:10:35

标签: jax-rs

在向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);
            }
        });
    });

网络服务:

@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;
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在jQuery请求上设置内容类型。如果您不这样做,则默认为application/x-www-form-urlencoded。仅仅因为您添加@Consumes(MediaType.APPLICATION_FORM_URLENCODED)并不意味着JAX-RS不会如何将表单数据转换为Disruptive。需要MessageBodyReader才能处理转换,但这并不存在。同样适用于MediaType.TEXT_HTML。如果没有转换器来处理转换,只需添加即可。删除这两个。你想要的是处理JSON转换,EE服务器中应该包含MessageBodyReader,它将JSON数据转换为任意POJO。

所以对于jQuery,只需添加

$.ajax({
  contentType: 'application/json'
})

那应该可以解决问题。