Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
- add attribute
contentType: 'application/json; charset=UTF-8'
- remove attribute headers from ajax call.
toing_toing
Updated on August 08, 2022Comments
-
toing_toing almost 2 years
I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function). Here is the ajax query from my test html page:
$(function(){ $('.message-button').on('click', function(e){ var resultDiv = $("#resultDivContainer"); $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 'type': 'POST', 'url': 'http://localhost:8080/xxxAPI/api/activity', 'data': { "baseItemId": "2" }, 'dataType':'json', 'success': function(data) { var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data); $("#resultDivContainer").text(xmlstr); }, 'error': function(jqXHR, textStatus, errorThrown) { alert(' Error in processing! '+textStatus + 'error: ' + errorThrown); } }); }) });
Also here is the part of my java code that accepts post requests:
@POST @Override @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void create(XxxxxActivity entity) { super.create(entity); }
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to
jsonp
, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.