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
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));
}
});
I am trying to manage a user session by making an ajax request to java code repeatedly
function sendSessionKeepAliveRequest() {
$.get('${URL}/sessionKeepAlive?nd=' + new Date().getTime());
}
and java code (spring framework used) handling this request:
#RequestMapping("/sessionKeepAlive")
public String dummySessionKeepAlive(HttpServletResponse response,
HttpServletRequest request) {
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
logger.error(e.getMessage());
}
if (writer != null) {
response.setContentType("application/json");
// Sending an empty JSON response.
Gson gson = new Gson();
writer.write(gson.toJson(""));
}
return null;
}
Now the issue is some times were are getting 302 Found instead of 200 OK which makes jsessionid change and session got time out.I have tested in on IE and FF and both of the browser have same behaviour.
Code is deployed on IBM websphere v7.0
Please help or any direction.Please feel free if any more inputs are required or I need to modify my question.
Kind Regards
You have encountered a so-called redirection: The url of the resource you've requested has changed. The new url is provided in the http header 'Location'.
You can either read out this location and issue another Request using this url or you can set up your response handling code to automatically follow the redirection.
Sample code:
function sendSessionKeepAliveRequest() {
$.ajax(
url: '${URL}/sessionKeepAlive?nd=' + new Date().getTime()
, statusCode: {
302: function ( jqXHR, textStatus, errorThrown ) {
var url_trg = jqXHR.getResponseHeader('Location');
$.get(url_trg);
}
}
});
Update
jquery ajax requests should handle 302 status codes automatically, so there might be some other problem. Could it possibly be a cross-domain issue ?
If the purpose is just only to alive session then no need to use GSON you can pass empty String and add one annotation
#ResposeBody
This will help you to get ajax response.
/*ajax request to servlet to perform update operation*/
var savedata={
video_Title:videotitle,
video_duration:videoduration,
video_Url:videourl,
video_Description:videodescription
};
$.ajax({
url:'videoUpdate',
type:'POST',
cache:false,
data: savedata,
contentType: "application/json; charset=utf-8",
success: function(response) {
alert("Updated Successfully");
},
error:function()
{
alert("oops sorry something went wrong. we apologize for the inconvenience");
}
});
/*Controller Class*/
#RequestMapping(value ="videoUpdate",method = RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Status updateVideo(#RequestBody Video video) {
try {
System.out.println("update servlet");
dataServices.updateVideo(video);
return new Status(1,"video updated Successfully");
}
catch (Exception e) {
return new Status(0,e.getMessage().toString());
}
}
My question is how to receive ajax-json request data in my servlet class.Is this is the correct way to catch a set of data from ajax in spring mvc.Or other annotation is required for avoiding 400 error!?
The 400 Bad Request seldom happens because the url viz videoUpdate could not be mapped to appropriate mapping.
This could be because you might not be passing the arguments required to make to point cut.
I would suggest you to inspect following portion of your code:
var savedata={
video_Title:videotitle,
video_duration:videoduration,
video_Url:videourl,
video_Description:videodescription
};
And make sure you are passing required parameters.
If you specify
contentType: "application/json; charset=utf-8",
that means you are expecting JSON data in return - if it's not valid JSON then it goes to the error block.
You are probably returning a string :
return new Status(0,e.getMessage().toString());
Try omitting the contentType line. Also posting browser console errors might help us determine the problem easier.
Note: If you want to specify the outgoing data type there's a dataType setting.
Assuming the URL you are hitting is correct, you could look at whether the fields of the Video class exactly match the JSON you are POSTing
I'm trying to call a Webservice that consumes a json object with post method .I did it then It wont work again don't know what is the problem.
here is my method
#POST
#Path("/post")
#Consumes("application/json")
#Produces("application/json")
public Response testClient(Client c) throws IOException {
System.out.println(c.getAdresseCl());
ResponseBuilder builder = Response.ok(c.getAdresseCl());
builder.header("Access-Control-Allow-Origin", "*");
builder.header("Access-Control-Max-Age", "3600");
builder.header("Access-Control-Allow-Methods", "*");
builder.header(
"Access-Control-Allow-Headers",
"X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
return builder.build();
}
to call this I used this
$.ajax({
type: 'POST',
url: "http://localhost:9080/FournisseurWeb/jaxrs/clients/post",
data: '{"adresseCl":"tunis"}',
dataType:'json',
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
}
});
well I remark that when I set the contentType to application/json the method changes to OPTIONS .
and when I don't use the content type I got "415 Unsupported Media Type " I dont know how to fix this. I passed too much time without results :(thank you for helping me
When attempting to make cross-domain AJAX requests in certain browsers, it is a common to see the HTTP Method change to OPTIONS in lieu of a more meaningful error message.
I noticed in your URL that you're including the protocol, domain, and port, which supports the theory that you're actually trying to make an AJAX request to a different domain/port combination than the originating context.
To clarify, even if your request is originating from localhost and targeting localhost, the ports (9080) and protocols (http) must also match.
Thus, if the page you loaded is "http://localhost:8080" and you're trying to make an AJAX request to "http://localhost:9080", the request will fail, may throw same-domain security errors, 415 Unsupported Media Type, and/or change the HTTP Method to OPTIONS.
One way to make sure you avoid this mistake is to only use full or relative paths when making AJAX requests, such as:
url: "/FournisseurWeb/jaxrs/clients/post",
This forces you to always make requests to the same domain.
Cross-domain Requests
If you do indeed require the ability to make cross-domain requests, this is possible, but only through two methods.
First, you can use a proxy, where you make an HTTP request to your domain and then forward the request onto another server. Servers need not be concerned with same-domain policies when sending and receiving data from one another.
Second, you can use JSONP, also known as script tag remoting, which involves exploiting the <script> element's ability to send requests across different domains.
// added callback= query parameter to convert this to JSONP
$.ajax({
type: 'POST',
url: "http://localhost:9080/FournisseurWeb/jaxrs/clients/post?callback=",
data: '{"adresseCl":"tunis"}',
dataType:'json',
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
}
});
NOTE: When using JSONP, your server must respond with the JSON wrapped up in a function call identified by the callback parameter. See the jQuery documentation for more in-depth details .
Other than that, you must make AJAX requests to the same domain the page was loaded from.
this is the method that consumes a text xml fomat and map it to an object to persist it next
#POST
#Path("/inscription")
#Produces(MediaType.TEXT_HTML)
public Response testClient(String s) {
ResponseBuilder builder = null;
try {
final String xmlString = s;
final StringReader xmlReader = new StringReader(xmlString);
final StreamSource xmlSource = new StreamSource(xmlReader);
final JAXBContext jaxbContext = JAXBContext
.newInstance(Client.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final Client client = (Client) unmarshaller.unmarshal(xmlSource,
Client.class).getValue();
System.out.println("nomCl : " + client.getNomCl());
System.out.println("prenomCl : " + client.getPrenomCl());
System.out.println("emailCl : " + client.getEmailCl());
System.out.println("numTel : " + client.getNumTel());
System.out.println("long_ : " + client.getLong_());
System.out.println("lat : " + client.getLat());
System.out.println("LoginCl : " + client.getLoginCl());
System.out.println("PasswordCl : " + client.getPasswordCl());
System.out.println("adresseCl : " + client.getAdresseCl());
EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("FournisseurWeb");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(client);
em.getTransaction().commit();
em.close();
factory.close();
builder = Response.ok("true");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
builder = Response.ok("false");
builder.header("Access-Control-Allow-Origin", "*");
builder.header("Access-Control-Max-Age", "3600");
builder.header("Access-Control-Allow-Methods", "POST");
builder.header(
"Access-Control-Allow-Headers",
"X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
return builder.build();
}
builder.header("Access-Control-Allow-Origin", "*");
builder.header("Access-Control-Max-Age", "3600");
builder.header("Access-Control-Allow-Methods", "POST");
builder.header(
"Access-Control-Allow-Headers",
"X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin");
return builder.build();
}
I use to call this method using ajax with this sample :
var x="<client><nomCl>Taarit</nomCl><prenomCl>Aymen</prenomCl><emailCl>aymen.taarit#gmail.com</emailCl><numTel>222</numTel><long_>1.66</long_></client>";
$.ajax({
url: 'http://localhost:9080/FournisseurWeb/jaxrs/clients/cl',
type: 'post',
scriptCharset: "utf-8" ,
dataType:"xml",
data: x,
success: function(data, status) {
console.log(data);
}
});
this is a jax-rs call with ajax POST using cross domain so hope that it helps :)
NOTE: The cross-domain call without JSONP is legal here because the server is returning the following header, which enables cross-domain AJAX!
builder.header("Access-Control-Allow-Origin", "*");
See Mozilla Developer Center page on Access-Control-Allow-Origin for more details.