Error 415 with Ajax request(Ajax, Spring) - java

I send Ajax request to my server, but server doesn't get responce.
PUT request:
function editNavigation() {
var flight={
id:idAction.replace('edit',''),
navigation:newNavigation
};
console.log(flight);
var prefix = '/airline/';
$.ajax({
type: 'PUT',
url: prefix +'flights/' + idAction.replace('edit',''),
data: JSON.stringify(flight),
headers:{contentType: "application/json"},
success: function(receive) {
$("#adminTable").empty();
$("#informationP").replaceWith(receive);
$("#hiddenLi").removeAttr('style');
},
error: function() {
alert('Error edited flight');
}
});
}
Controller:
#RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String updateFlight(#PathVariable("id") String id, #RequestBody FlightDto flightDto) {
String returnText = "Flight edited successful";
String str1 = flightDto.getNavigation();
logger.info(str1);
String str2 = id;
logger.info(str2);
return returnText;
}
Browser console:
Object {id: "5", navigation: "sdf"}
PUT http://localhost:8080/airline/flights/5 415 ()
Why I get error 415?
Why my controller doesn't send responce?

415 resonance code is Unsupported Media Type.
If your service expect POST(or any kind) request and if user send
PUT request then server will give this kind of response.
if user send wrong MediaType then also this type of error comes.
In your code, I think you have configure wrong MediaType which is APPLICATION_JSON_VALUE. you can specify MediaType.APPLICATION_JSON.
I think this will helps.

Related

AJAX POST method to Spring RestAPI not working

I'm trying to send a large form of data to my server side, using jQuery AJAX and sending it to a RESTful service made in the Spring Framework. And the form as arrays of unknown sizes, so am trying to get the auto serializing to work. But I can't even get it to work with a simple test example.
It seems to not be able to match my JSON file to the input class. So I must be doing something wrong. But I have not been able to see what I'm doing wrong based on the tutorials I have been trying to follow.
Here is my AJAX call
var test = JSON.stringify({
name : "hallo", lastname : "there"
});
console.log(test);
$.ajax({
type: "POST",
url: "/SpringTest_war_exploded/test",
contentType: "application/json",
data: test,
success: function (returnValue) {
console.log("success");
console.log(returnValue);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log (XMLHttpRequest);
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
Here is my server-side method.
#PostMapping(value = "/test", consumes = "application/json")
#ResponseBody
public String testajax(#RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
Here is the class I'm trying to match it with
public class TestAutoCreate {
private String name;
private String lastname;
public TestAutoCreate(String name, String lastname) {
this.name = name;
this.lastname = lastname;
}
// the getters and setters
...
}
And here is the error massage I get
The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
If I remove the #RequestBody TestAutoCreate test from the server side method, then the call works fine. It is only
The problem at here
#PostMapping(value = "/test", consumes = "application/json")
#ResponseBody
public String testajax(#RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
It is RESTful controller, but return view. You must return RESTful response, what has content type is Content-Type: application/json .
See authority example: https://spring.io/guides/tutorials/rest/

Why does Spring MVC respond with 415 for an Ajax query requesting JSON?

I've read 3/4 posts on Stack plus many other examples to try figure this out but I've no clue ! Need some pointers please !!
Creating my first Ajax update through Spring-MVC and I keep getting a Status 415 being returned by my submission with The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request accept
JQuery... Version 3.1.1
function updateScore () {
$("div#results").append("<p>Posting User/Game ID " + this.id + " Value " + this.value + "</p>");
var prediction = {}
prediction["id"] = this.id;
prediction["value"] = this.value;
$.ajax({
type : "POST",
contentType : "application/json",
url : "/tournament/setPrediction.html",
data : JSON.stringify(prediction),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
displayResult(data, "success");
},
error : function(e) {
console.log("ERROR: ", e);
displayResult(e, "error");
},
done : function(e) {
console.log("DONE");
displayResult(true, "done");
}
});
}
Controller... Spring version 4.3.5
#RestController
public class PredictionAjaxController {
#ResponseBody
#RequestMapping(value = "/setPrediction.html", consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST, headers="Accept=application/json")
public Prediction setUserPrediction(#RequestBody PredictionPojo prediction) {
Prediction result = new Prediction();
System.out.println("AJAX call made in controller");
return result;
}
}
Finally a very simple POJO for the JSon to map to
public class PredictionPojo {
private String id;
private String value;
Getters & Setters... ()
}
I've added different things onto the controller now to try and resolve, didn't start with it all ! I'm completely confuddled !
Should be so simple...
DH
You have an error in your ajax call, you are sending a string instead of a JSON object. Also I don't think is necessary to specify the consumes and headers attributes in you #RequestMapping annotation in your setUserPrediction method, The PredictionAjaxController is already defined as a RestController. Your ajax should be:
$.ajax({
// .......
data : prediction,
// .......
});

Consume Cookie and JSON with JAX-RS Jersey Service

I am sending these data to Restful Web Service (Jersey) using jQuery code and the method POST:
var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);
And with this data, I am sending a cookie. The data in te cookie come from an external API.
The problem what I am facing is how to receive the cookie value and the dataString together.
Here's my Java code to read a Cookie :
#POST
#Path("cookie")
public String cookie(#CookieParam("L14c") String str) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
return str;
}
And for the data, I can do like this :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("cookie")
public String cookie(DataString dataString) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
return "ok";
}
But when I combine the two methods to accept cookie and the JSON dataString, I got Error 415, Unsupported media type!
I tried to look on HTTP Headers, but I can access only cookies.
The problem is with the jQuery request. It looks like the Content-Type is defaulting to application/x-www-form-urlencoded. You should use a Browser debugger like Firebug. Makes it easier to spot these kind of things.
From what I've tested, it should work with something like
$.ajax({
url: theUrl,
type: "POST",
data: JSON.stringify(dataString),
dataType: "json",
contentType: "application/json",
success: function(response) {
alert(JSON.stringify(response));
}
});

Http status 404 (Not Found) on jquery ajax GET to spring controller?

My spring controller contains such get handler :
#RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Region> getRegionsFor(#RequestParam(value = "countryName") String countryName,
#RequestParam(value = "geonameId") Long geonameId) {
logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
RegionInfo regionInfo = restTemplate.getForObject(
"http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
RegionInfo.class, geonameId);
return regionInfo.getRegions();
}
#Controller is mapped to /hostel. So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754
When I type in chrome browser
http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754
It returns json response as expected!!!
But I want to access this url with the following ajax call made with jquery:
$.ajax({
headers : {
'Accept' : 'application/json'
},
url : '/hostel/country',
dataType : 'json',
data : {countryName:"Albania",geonameId:783754},
type : 'GET',
async : true,
success : function(response) {
console.log("response=" + response.join(','));
},
error : function(errorData) {
console.log("data on fail ");
printObject(errorData);
}
});
As you guess this doesn't work at all. Http status 404 (Not Found) is returned to error: handler .
How can I solve this?
The url in the ajax call is relative to the hostname. You need to add your web application context
url : '/HostMe/hostel/country',

response status from server to client

In my app I want to respond from server to client the status of the operation, for example, from client sends data in format json to server and I want that this responds whit status of the operation, if these data have inserted correctly in database to send status 200,...
I now have this.
Client:
function sendAjax() {
//I build the params necessary to send to server in format json
$.ajax({
url: "/url",
type: 'POST',
dataType: 'json',
data: param,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.id );
},
error: function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
alert();
}
Server:
Controller.java
#RequestMapping(value = "/", method = RequestMethod.POST)
public #ResponseBody
ResponseJson post (#RequestBody String string){
//I have the operations necessary to insert in database
ResponseJson pruebaJson = new ResponseJson ();
pruebaJson.setId (id);
return pruebaJson;
}
ResponseJson.java
public class ResponseJson implements Serializable
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
How will I process the status that server send to client? this is, if I get status 200 or other status.
My app is realized in spring-mvc and I use javascript with ajax to send data in format json from client to server.
Thanks
You can do it by :
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
},
200: function() {
alert("insert done..!!!");
},
}
});
This may help you.
See JQuery API for more option.
EDIT : on the basis of my understanding you want to check status code inside success or error function for that
success: function(data , textStatus, jqXHR) {
alert(data.id );
var statusCode = jqXHR.status
if(statusCode == 200 ){
//Your code execute if status is 200
}
}
like wise you can do it in error function also.
In your ajax call success function executes when server sends status 200 code. other than that your error function only executes.
If you want to handle error status separately you can handle in error function with return status.

Categories