HTTP 状态 415 - JQUERY 中的 AJAX 调用不受支持的媒体类型到使用 JERSEY 实现的 Restful WS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14863274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:00:46  来源:igfitidea点击:

HTTP Status 415 - Unsupported Media Type for AJAX call in JQUERY to Restful WS implemented with JERSEY

jqueryjerseyhttp-status-code-415

提问by mik

Hi I am trying to post json data to Restful WS implemented with Jersey. I am posting data through jquery-ajax. Why am I geting HTTP Status-415 unsupported Media type? Thank you.
Click here for screenshot of firebug description

嗨,我正在尝试将 json 数据发布到使用 Jersey 实现的 Restful WS。我正在通过 jquery-ajax 发布数据。为什么我得到 HTTP Status-415 不受支持的媒体类型?谢谢你。
单击此处查看萤火虫描述的屏幕截图

 //post method handler 
      @Path("/newentry")
        public class NewEntry {

            @POST
            @Consumes(MediaType.APPLICATION_JSON)
            public Response newEntry(String data) {
                    //doStuff
        }
    }
    // ajax call 
         $.ajax({
                 url: "http://localhost:8080/FirstRestWebService/rest/newentry",
                 type: "post",
                 data: formToJSON(),
                 dataType : "json",
                 success: function(data){
                alert("success");
                  },
               error:function(jqXHR, textStatus, errorThrown) {
                    alert("failure");
                  }   
            }); 

         function formToJSON() {
                return JSON.stringify({
                    "name": $("input#emp_name").val(),
                    ...
                    "username": $('input#username').val(),
                    "password": $('input#password').val()
                    }); 

Click here for screenshot of firebug descriptionI was able to test the WS successfully by Jersey Client. What is wrong in the above AJAX call? Thank you.

单击此处查看萤火虫描述的屏幕截图我能够通过 Jersey Client 成功测试 WS。上面的 AJAX 调用有什么问题?谢谢你。

回答by jgm

In your AJAX call you need to set your content type:

在您的 AJAX 调用中,您需要设置内容类型:

contentType: "application/json"

回答by DàChún

You must declare the JSON dependency. Please try to add the following dependency to your pom.xml.

您必须声明 JSON 依赖项。请尝试将以下依赖项添加到您的 pom.xml。

 <dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>0.98</version>
</dependency>