Error while calling web service, operation can not be completed - iphone

I am call web-service and I am getting 0 bytes in response as well as getting error like below:
Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0xa9b8ef0 {NSErrorFailingURLKey=http://quantuminfoways.com/crossfit_wodgenius/webservice/sync.php, NSErrorFailingURLStringKey=http://quantuminfoways.com/crossfit_wodgenius/webservice/sync.php}
And i am passing data as the
sample link.
And in data i am passing this:
{
createwod = {
deletedcreatewod = (
);
newcreatewod = (
);
};
favorite = {
deletedfavorite = (
);
newfavorite = (
);
};
gym = {
deletedgym = (
);
newgym = (
);
};
workoutlog = {
deletedworkoutlog = (
);
deletedworkoutlogtime = (
);
newworkoutlog = (
);
};
}
Can any one help me to solve it?
thanks

One of the reason of error "kcferrordomaincfnetwork error 303" when you are calling a POST method as GET.

A 303 error is a redirect error.
You might want to check out the automatic handling of redirects with NSURLConnection:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/RequestChanges.html
If you'd like to handle it manually, the redirect url is in the response's 'Location' header. Here's how you can grab it in your connection:didReceiveResponse delegate method.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
// ... if the response status is 303 ...
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSString* location = [[httpResponse allHeaderFields] valueForKey:#"Location"];
// do whatever with the redirect url
}
}
You coul also try urlEncoding your url including the data. Try what happens if you just call the following URL: http://quantuminfoways.com/crossfit_wodgenius/webservice/sync.php?udid=123&new=yes&uid=45&data=%20%7B%20createwod%20=%20%7B%20deletedcreatewod%20=%20(%20);%20newcreatewod%20=%20(%20);%20%7D;%20favorite%20=%20%7B%20deletedfavorite%20=%20(%20);%20newfavorite%20=%20(%20);%20%7D;%20gym%20=%20%7B%20deletedgym%20=%20(%20);%20newgym%20=%20(%20);%20%7D;%20workoutlog%20=%20%7B%20deletedworkoutlog%20=%20(%20);%20deletedworkoutlogtime%20=%20(%20);%20newworkoutlog%20=%20(%20);%20%7D;%20%7D

Related

Swift - Is it possible to decode the HTTP response headers, for request limiting?

I am decoding a JSON from an API using JSONDecoder and URL session. It works great
URLSession.shared.dataTask(with: request) { (data, theResponse, error)
Within "theResponse" (which I am not decoding), the last key is "X-RateLimit-requests-Remaining":
<NSHTTPURLResponse: 0x6000033ec300> { URL: myUrl } { Status Code: 200, Headers {
Connection = (
"keep-alive"
);
"Content-Encoding" = (
gzip
);
"Content-Length" = (
1913
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 28 Sep 2020 14:34:35 GMT"
);
Server = (
"RapidAPI-1.2.6"
);
"X-RapidAPI-Region" = (
"AWS - eu-central-1"
);
"X-RapidAPI-Version" = (
"1.2.6"
);
"X-RateLimit-requests-Limit" = (
100
);
"X-RateLimit-requests-Remaining" = (
68
);
} }
Since the above is not JSON, is it possible to decode these values into a type, that I can then use for rate limiting purposes?
For example, limiting requests within my app when "X-RateLimit-requests-Remaining" reaches 10
Thanks
These are already decoded for you, into a [AnyHashable: Any] dictionary. To fetch this particular one, you'd check it with something along these lines:
if let remaining = theResponse.allHeaderFields["X-RateLimit-requests-Remaining"]
as? Int { ... }

How do I get the value of collection.find(connect.data).fetch()?

I am trying to create a meteor RESTful API for my app based on this The Meteor Chef online tutorial. The HTTP package is installed in the beginning of the tutorial, in order to test the RESTful API once the API development is completed.
I am currently in the testing phase and cant seem to get my GET Methods used to retrieve data from my collection to work.
Find below my GET Method code:
methods: {
pescrow: {
GET: function( context, connection ) {
var hasQuery = API.utility.hasData( connection.data );
console.log("hasQuery value == " +hasQuery+ " on line 183");
if ( hasQuery ) {
connection.data.owner = connection.owner;
console.log("Your in GET::hasQuery: Line 187 " + connection.data );
var getPescrows = recipientsDetails.find( connection.data ).fetch();
console.log("getPescrows value: " +getPescrows+ " Line 203");
if ( getPescrows.length > 0 ) {
// We found some pescrows, we can pass a 200 (success) and return the
// found pescrows.
console.log("getPescrows found Line 205");
API.utility.response( context, 200, getPescrows );
}
else {
console.log("getPescrows NOT found Line 208!");
// Bummer, we didn't find any pescrows. We can pass a 404 (not found)
// and return an error message.
API.utility.response( context, 404, { error: 404, message: "No Pescrows found, dude." } );
}
}
else {
// Our request didn't contain any params, so we'll just return all of
// the pescrows we have for the owner associated with the passed API key.
var getPescrows = recipientsDetails.find( { "owner": connection.owner } ).fetch();
API.utility.response( context, 200, getPescrows );
}
}
}
}
I test my API via the Chrome console by pasting in the below code:
HTTP.get( "http://localhost:8000/paymentC2B/v1", {
params: {
"api_key": "b21d83ef267bd829a9d732551270c718",
"paymentStatus": "Pending",
"recipientNumber" : "0705087633"
}
}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
And the response I get in the terminal is:
hasQuery == true Line 183
Your in GET::hasQuery: Line 187 [object Object]
getPescrows value: Line 203
getPescrows NOT found Line 208!
When I run the query below in the console it successfully yields:
recipientsDetails.find({paymentStatus:"Pending", recipientNumber: "0705087633"}, {sort: {paymentDate: 'desc' }}).fetch()
Showing:
[{…}]
0
:
key : "b21d83ef267bd829a9d732551270c718"
paymentDate : "2018-04-02 15:15:49"
paymentStatus : "Pending"
recipientAmount : "500"
recipientNumber : "0705087633"
_id : "uSsCbdBmmhR2AF2cy"
__proto__ : Object
length : 1
__proto__ : Array(0)
It seems like the issue is in the recipientsDetails.find( connection.data ).fetch(); query. Can someone kindly point out where I am going wrong in my code?
Looking forward to your response.
When you test your params include api_key. I'm betting this key does not appear in your recipientsDetails collection.
Instead of just doing:
connection.data.owner = connection.owner;
Try:
connection.data.owner = connection.owner;
delete connection.data.api_key;

How to send post data to the server in angular datatables?

please provide any code or any example or any link.
vm.dtOptions = DTOptionsBuilder.fromSource( baseApi + '/NH/dashboard' ).withFnServerParams( serverParams );
function serverParams ( aoData ) {
aoData.push( jsonObj );
}
it gives error..
DTOptionsBuilder.fromSource(...).withFnServerParams is not a function

facebook messenger bot encoding error

I have written sample echo message bot using facebook messenger api and wit.ai actions.
My message from facebook page is received and the proper action function defined using wit api's is also getting called. However
while returning the response, i am getting followin error as -
Oops! An error occurred while forwarding the response to : Error: (#100) Param message[text] must be a UTF-8 encoded string
at fetch.then.then.json (/app/index.js:106:13)
at process._tickCallback (internal/process/next_tick.js:103:7)
Here is the function which is used to return the response -
const fbMessage = (id, text) => {
const body = JSON.stringify({
recipient: { id },
message: { text },
});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
return fetch('https://graph.facebook.com/v2.6/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);`enter code here`
}
return json;
});
};
I have copied this function from the messenger.js file from the documentation since i am just trying the POC.
I checked the values for text and id in this function and verified using console.log statements and those are coming properly.
Can some experts help me to solve this error?
Note - I tried encoding the text using text.toString("utf8"); but it returns the encoding string as [object object] and thats the
response i get from bot. so it doesnt work.
Get the latest code from node-wit, there is a change in facebook id usage,
According to Facebook:
On Tue May 17 format of user and page ids delivered via webhooks will
change from an int to a string to better support default json encoder
in js (that trims long ints). Please make sure your app works with
string ids returned from webhooks as well as with ints.
Still you are getting issue with the api try to add if(event.message && !event.message.is_echo) condition as shown in below code.
// Message handler
app.post('/webhook', (req, res) => {
const data = req.body;
if (data.object === 'page') {
data.entry.forEach(entry => {
entry.messaging.forEach(event => {
if (event.message && !event.message.is_echo) {
const sender = event.sender.id;
const sessionId = findOrCreateSession(sender);
const {text, attachments} = event.message;
if (attachments) {
fbMessage(sender, 'Sorry I can only process text messages for now.')
.catch(console.error);
} else if (text) {
wit.runActions(
sessionId, // the user's current session
text, // the user's message
sessions[sessionId].context // the user's current session state
).then((context) => {
console.log('Waiting for next user messages');
sessions[sessionId].context = context;
})
.catch((err) => {
console.error('Oops! Got an error from Wit: ', err.stack || err);
})
}
} else {
console.log('received event', JSON.stringify(event));
}
});
});
}
res.sendStatus(200);
});
Reference:
no matching user bug
no matching user fix

Stream Error when calling REST services using AS3

I am trying to do a REST client using AS3, I am following this tutorial: http://help.adobe.com/en_US/as3/dev/WSb2ba3b1aad8a27b061afd5d7127074bbf44-8000.html
My code is the following:
import flash.events.Event;
import flash.events.ErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
var url:String = "https://localhost:8443/restcomponent/tesimalex";
var requestor:URLLoader = new URLLoader();
function restServiceCall():void
{
trace("Calling REST Service...");
//Create the HTTP request object
var request:URLRequest = new URLRequest( url );
request.method = URLRequestMethod.GET;
//Add the URL variables
// var variables:URLVariables = new URLVariables();
// variables.method = "test.echo";
// variables.api_key = "123456ABC";
// variables.message = "Able was I, ere I saw Elba.";
// request.data = variables;
//Initiate the transaction
requestor = new URLLoader();
requestor.addEventListener( Event.COMPLETE, httpRequestComplete );
requestor.addEventListener( IOErrorEvent.IO_ERROR, httpRequestError );
requestor.addEventListener( SecurityErrorEvent.SECURITY_ERROR, httpRequestError );
requestor.load( request );
}
function httpRequestComplete( event:Event ):void
{
trace( event.target.data );
}
function httpRequestError( error:ErrorEvent ):void{
trace( "An error occured: " + error.toString() );
}
The only diference between my code and the one in the tutorial is the URL variables, that I commented, and the url used.
My REST service is a simple GET, if I type the url in the browser it shows me the JSON returned.
But in my AS3, when I call the method restServiceCall() it returns the following error:
Error opening URL 'https://localhost:8443/restcomponent/tesimalex?' An
error occured: [IOErrorEvent type="ioError" bubbles=false
cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL:
https://localhost:8443/restcomponent/tesimalex?"]
Anyone knows whats wrong?
Ok... It was a security issue... I disabled SSL in my server and then my flash app managed to comunicate with my REST service.