webservice call using Post - java

I am new to webservice and ajax .. I tried to call a webservice using POST method.
I tried to invoke it using Postman (Google chrome App) and I was getting the response but when I tried using Ajax I am getting error
Following are the things I did:
My Code: (I wrote a JS in which I included following code and tried all the commented options too ):
$.ajax({
crossDomain: true,
url : 'https://yxyxyxyxyx/search/v1/query.json',
type : 'POST',
dataType : "json",
data: {appId: "a9b475a079",query: "dhcp"},
//async : true,
//headers: {"Content-type": "application/json"},
headers: { 'Access-Control-Allow-Origin': '*' },
//contentType: "application/json; charset=utf-8",
//headers: ('Access-Control-Allow-Methods: GET, POST, OPTIONS'),
//headers: ('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With'),
//headers: ('Access-Control-Allow-Credentials: true'),
// Access-Control-Allow-Origin: "http://localhost:8080",
// headers: { 'Access-Control-Allow-Origin': '*' },
//userAgent : 'Mozilla/22.0',
success: function(data){
alert("hi success");
},
error: function(data) {alert("An error occured: " + data.status + " " + data.statusText);
});
I am getting the alert in the error and getting following error while debugging:
XMLHttpRequest cannot load https://www.sample.search/v1/query.json. The request was redirected to 'https://www.sample/obrareq.cgi?wh%3DCCI-STG4%20wu%3D%2Fuesps%…n-tools-stage.cisco.com%20ru%3D%252Fuesps%252Fsearch%252Fv1%252Fquery.json', which is disallowed for cross-origin requests that require preflight.
I tried all the options to resolve the CROS option in which I found on net… do we have any other way to resolve it.
Can someone help me if we can do it using a java class that will also serve the purpose

Related

Not able to get response from the Java application using the "request" in ReactJS app, however API is working fine with postman

I copied postman code and try to run it from the ReactJS app but it is giving error "Uncaught Error: Error: Invalid URI "/dologin"
I also used setupProxy.js file in the reactjs app but it is not working.
Here is my code from Postman.
var request = require("request");
var options = {
method: 'POST',
url: 'http://x.x.x.x:8080/dologin',
headers: {
'postman-token': 'b8754e2-974a-98fc-08e8-d40215dd226c',
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YW21547gW'
},
formData: {
username: 'username',
password: 'password'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
If I remove CORS from the server then I am able to get the response but token is not coming in the header, however it is coming if I use Postman.
Please help, thanks

React app not sending headers to java server

I searched a lot on the Internet, but I didn't find anything helpful for my problem.
I have a java server and a react client. My server is using jwt for authentication and returns a token to my client.
When I try to send data with a post method, my client does not send the headers, so my server returns an "Unauthorized" message. I tried to send the same request from Postman and ARC(Advanced Rest Client) and it works.
Here is my client code:
fetch(url, {
method: 'POST',
crossDomain: true,
mode: 'no-cors',
body: JSON.stringify(data),
headers: {
'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
});
I tried using axios too and I have the same problem.
Also my server has #CrossOrigin(origins = {"*"}) annotation in all controller classes.
I don't know if my problem is with the client or with the server and why is working using Postman and ARC.
You are using mode: no-cors which basically strips out all headers which are not simple headers: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
You should enable CORS and allow your domain on the server.

How to call an AXIS web service via AJAX?

I'm very new to web services. I used eclipse and some tutorials from the web to create a simple web service called DeScriptor which I uploaded to a Tomcat server. It's accessible through this URL
http://www.xwizard.de:8080/services/DeScriptor
and according to the message written out there, it appears to be working (right?).
So far, so good, but now I don't know how to call it. The service has a single method String retrieveSVGFromScript(String scrp) which I tried to call with this AJAX code:
var hallowelt = "Hallo Welt";
var params = JSON.stringify({scrp: hallowelt});
$.ajax({
type: "POST",
url: "http://www.xwizard.de:8080/services/DeScriptor/retrieveSVGFromScript",
data: params,
dataType: "json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (msg) {
console.log(msg.d);
},
error: function (xhr, status, error) {
// Some error handling.
}
});
hoping that I'd get the result string of the method by msg.d, but instead I got this not so informative error message:
jquery.js:8630 POST http://www.xwizard.de:8080/services/DeScriptor/retrieveSVGFromScript 500 (Internal Server Error)
Can somebody point me in the right direction?
EDIT: You can find the WSDL here: http://www.xwizard.de:8080/services/DeScriptor?wsdl
You are trying to call a server webservice using REST style (i.e. setting content-type, providing params as JSON message, etc.).
But the webservice expects a SOAP message. An example how to send a SOAP message with Javascript can be found here.

Not able to call servlet using ajax

I am trying to call servlet using ajax on click event. And from that servlet I am calling google auth end point. I tried set header to the servlet I am calling but I an not able to get rid of this error
XMLHttpRequest cannot load
https://accounts.google.com/o/oauth2/auth?client_id=2536-a…nid%20profile%20email&state=F1BFD3804&display=popup.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
Here is the code
$.ajax({
type: "GET",
url: "/url-for-servlet",
dataType: "jsonp",
contentType: 'application/json',
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
alert("yippy");
console.log(data);
}
});
On servlet I added to response
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.addHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "x-requested-with");
Any idea what I am missing here? Thanks for the help.
This is a standard security restriction : JS cannot make requests to domains other than their own. So you have an application on localhost making Ajax calls to an application on accounts.google.com - not allowed by default.
See this question
AJAX usually doesn't allow to call other domain API from it. It is called CSRF attack. The solution for you is, Post the data to your server servlet and do the action required there in the backend(Servlet).

Can't get the Rest Post response in Jquery Ajax post call

I am calling the Rest call using the Ajax post method but i get the below error or response.
{"readyState":0,"status":0,"statusText":"error"}
Even i enable the cors($.support.cors = true; ) and crossDomain (crossDomain: true (add in headers)).
Here is the sample request:-
function() {
$.support.cors = true;
var evergentData = {
"UpdateContactRequestMessage":{
"channelPartnerID":"123456",
"email":"greg#gmail.com",
"firstName":"greg",
"lastName":"chappel",
"externalId":"GC123",
"sessionToken":"f53095854bb230996f54fe32ed5a63f68c7718c7"
}
};
//GetProducts();
jQuery.ajax({
type: 'POST',
url: 'url for rest api call',
contentType: "application/json",
Accept: "application/json; charset=utf-8",
dataType: 'json',
data: evergentData,
//data: JSON.stringify(evergentData),
crossDomain: true,
processData: true,
headers: { 'access-control-allow-origin': '*',
},
success: function(resp){
// we have the response
alert("Server said123:\n '" + resp + "'");
},
error: function(e){
alert('Error121212: ' + e);
alert(e.toString());
console.log('my message' + e);
console.log('tables: ' + JSON.stringify(e));
}
});
};
But i tested this Restapi call in the 'postman' google chrome extension i got the response(successfully got the response).
Here is the response headers:-
access-control-allow-headers → client_type, content-type, accept, accept-language, auth_token_base64, appID, accept-encoding, content-length, x-requested-with
access-control-allow-methods → POST, GET, OPTIONS, DELETE
access-control-allow-origin → *
allow → GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
content-length → 92
content-type → application/json
x-frame-options → sameorigin
x-webobjects-loadaverage → 0
Anyone help me why i didn't get response from rest api call in JqueryAjax post calls.
Thank's advance.
It is important to understand that access-control-allow-origin': '*' in REQUEST header does nothing.
The Access-Control-Allow-Origin header must be in the RESPONSE header of the service you are calling. So the service regulates who is allowed to call the resource, thus service must add your app URL to it's RESPONSE Access-Control-Allow-Origin header.
Also note that wildcard * does not work for resources accessed over HTTPS. For resources over HTTPS ONLY absolute paths are valid.
Why Postman works? Cause it ignores the headers and policies while browser does not.
More reading:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Categories