简体   繁体   English

向Jax-rs服务发出Ajax Post请求

[英]Ajax Post request to a Jax-rs service

I'm trying to do a simple post request from a browser and 415 Unsupported Media is show in browser's console, in the console it says too that the Type is text/html , maybe I'm mising something stupid here but seriously I'm doing post request from an android client and everything is find with the server side, so i guess (since I'm not familiar with js) it's a javascript problem I'm having here, here are the portions of interest of the code: 我正在尝试从浏览器执行一个简单的发布请求,并且在浏览器的控制台中显示415 Unsupported Media ,在控制台中它也表示Typetext/html ,也许我在这里误解了一些愚蠢的东西,但是我很认真从android客户端执行发布请求,并且一切都可以在服务器端找到,所以我猜(因为我对js不熟悉),这是我在这里遇到的一个javascript问题,这是代码中感兴趣的部分:

ajax (this function is called send and it does some things before to create the json, that part it's ok and tested, the json is being genereated successfully): ajax(此函数称为send ,它在创建json之前做了一些事情,可以确定并测试了该部分,成功生成了json):

$.ajax({
        url: 'webresources/serverConfig/save/',
        type: 'post',
        dataType:'json',
        data: jsonObj
    });

how i call the javascript in the HTML form: 我如何以HTML形式调用javascript:

<form action="javascript:send()"  method="post">

JAX-rs service: JAX-RS服务:

@Path("serverConfig/")
public class ConfigurationSaverService {

@POST
    @Path("save/")
    @Consumes(MediaType.APPLICATION_JSON)
    public void save(Configuration configuration){
    //config stuffs here.
}

Edit: due to @adrianplattner's answer, it's important to say that I'm using glassfish 4.0 , so i didn't need to add jersey's dependencies, I also try glashfish 3.1 and still get the same HTTP error. Edit:由于@adrianplattner的回答,重要的是要说我正在使用glassfish 4.0 ,所以我不需要添加球衣的依赖项,我也尝试了glashfish 3.1并仍然收到相同的HTTP错误。

EDIT 2: Header: EDIT 2:标头:

 headers: { 
    'Accept': 'application/json',
    'Content-Type': 'application/json' 
},

you can add jersey dependency: 您可以添加球衣依赖项:

 <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-json</artifactId>
     <version>1.11</version>
 </dependency>

that should resolve ur problem 那应该解决你的问题

Default Content-Type of jQuery.ajax() call is application/x-www-form-urlencoded; charset=UTF-8 jQuery.ajax()调用的默认Content-Typeapplication/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 (see documentation ) but you're expecting to consume application/json in your JAX-RS resource. application/x-www-form-urlencoded; charset=UTF-8 (请参阅文档 ),但是您希望在JAX-RS资源中使用application/json Set the contentType parameter of your call to application/json . 将您的调用的contentType参数设置为application/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM