Spring Rest Service throwing HTTP Status 415 - java

Hi I am trying to call a Spring rest service from angular but I am getting the below error. Even from The Postman I am getting the same error.It looks like something is wrong with the rest service, which is not accepting the json request data
HTTP Status 415 : The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. Thanking everyone in advance.
Below is the code
**Angular Code**
var req = {
method: 'POST',
url: 'http://localhost:9050/FastTrackALM/retrieveData/getEpicData',
headers: {
'Content-Type': 'application/json'
},
data: {'epicId': '1' }
}
$http(req).then(function(response){
console.log(response);
}, function(response){
console.log(response);
});
**REST SERVICE**
#RequestMapping(method=RequestMethod.POST,
value="/getEpicData",
consumes={"application/json"},
produces={"application/json"})
#ResponseBody
#ResponseStatus(code = HttpStatus.OK)
public DataActionObject insertStudentDetails(#RequestBody epicForm1 student){
DataActionObject dataActionObject = new DataActionObject();
dataActionObject=epicBusinessBean.getEpicData(student.getEpicId(), dataActionObject);
return dataActionObject;
}
DataActionObject is my custom class that holds the json date to be returned to client along with message an code

Related

post method is not going to success part in angular

I am writing an angular with java project for this I have wrote a java rest service and I am calling it from my angular client with post method. it is able to call the rest service but it is not coming to client side.
I kept an alert in success. It is not printing but in chrome network tab the status is showing 200.
Angular: -
uploadFileToActivity() {
const endpoint = 'http://localhost:8090/sendmails';
let config = {headers: new HttpHeaders({})};
const formData: FormData = new FormData();
formData.append('fileupload', this.fileToUpload);
this.httpClient.post(endpoint, formData).subscribe(data => {
alert();
})
}
Java service: -
#PostMapping(value = "/sendmails", headers = "content-type=multipart/*")
public ResponseEntity<String> sendEmails(#RequestParam("fileupload") MultipartFile ExcelDataFile) {
return new ResponseEntity<String>("Success", HttpStatus.OK);
}
I want to do some functionality in success, but the call is not coming to success part.
I got an error in the console.
error: {error: SyntaxError: Unexpected token S in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "Success"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8090/sendmails"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8090/sendmails"
__proto__: HttpResponseBase
You are returning a text and not a JSON object from your java service. You can fix this by specifying the responseType in your post call:
this.httpClient.post(endpoint, formData, { responseType: 'text' })
You can also think about returning a JSON from your JAVA endpoint, but that's up to you

React fetch to Java backend returning null

I currently have a react button that should be sending data from the state to a servlet via post. The server is getting hit from the fetch method but the data appears to be null.
fetch(
"http://localhost:8080/askQuestion",
{
method: "post",
body: {
question: this.state.value
},
headers: {
"Content-Type": "application/text"
}
}
).then(console.log(this.state.value));
The value in my request object for both body and question are null
request.getParameter("question");
request.getParameter("body");
You can use getInputStream() or getReader() to read body attributes of the requests.
Here is an easy (not conventional) way to get your work done:
Write your body attributes in headers:
headers: {
"Content-Type": "application/text",
'question': this.state.value
}
In backend, use request.getHeader("question") to get the value.
You can try sending json data as the body of your post request
fetch('http://localhost:8080/askQuestion', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({ question: this.state.value })
}).then(res => res.json())
.then(res => console.log(res));

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