HTTP Status 415 - Unsupported Media Type for AJAX

2019-04-29 19:56发布

问题:

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

 //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 description I was able to test the WS successfully by Jersey Client. What is wrong in the above AJAX call? Thank you.

回答1:

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

contentType: "application/json"


回答2:

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

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