How to catch an elusive loader error in AS3 - actionscript-3

I'm trying to get some data from a php script using a loader and VARIABLES data format. Here's the code I have:
myUrlResults = new URLRequest("http://[...]/getData.php");
myUrlResults.method = URLRequestMethod.GET;
myResultsLoader = new URLLoader();
myResultsLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myResultsLoader.addEventListener(Event.COMPLETE, sendEventCompleteHandler);
myResultsLoader.addEventListener(IOErrorEvent.IO_ERROR, sendEventErrorHandler);
myResultsLoader.load(myUrlResults);
And
function sendEventCompleteHandler(e:Event) {
trace('Ok.');
}
function sendEventErrorHandler(e:IOErrorEvent) {
trace('Error occured:' + e);
}
As you know, Flash gives you a nasty error if the php file is not formatted properly.
But my .php file returns something like this var1=5&var2=10 and everything works great. However, sometimes, the server has issues and returns "Too many connections." which is something Flash doesn't like, because it's not a variable - value pair and I get an error like this:
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables$iinit()
at flash.net::URLLoader/flash.net:URLLoader::onComplete()
How to catch this error??

try set
myResultsLoader.dataFormat = URLLoaderDataFormat.TEXT;
and in your complete handler get the variables yourself after verify the result.
You can use a URLVariable.decode() and try/catch it there.

Related

JSON - WepAPI - Unexpected character encountered while parsing value

ANY help will be greatly appreciated
I have a Generic class that facilitates WebAPI calls, Its been in place for quite sometime and has had no issue. Today I'm getting an error and not sure where to track the problem. the exact error is
{"Unexpected character encountered while parsing value: [. Path 'PayLoad', line 1, position 12."}
what I'm getting back as the result of the call is
"{\"PayLoad\":[\"file_upload_null20180629155922²AAGUWVP2XUezeM3CiEnSOw.pdf\"],\"Success\":true,\"Message\":\"1 File(s) Uploaded\",\"Exceptions\":[]}"
Which looks right and is what I expect back from the service call
Here is the method that I'm calling that suddenly quit working, and its failing on the last line
public static TR WebApiPost(string serveraddress, string endpoint, object data)
{
HttpResponseMessage msg;
var clienthandler = new HttpClientHandler
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(user, password, domain)
};
using (var client = new HttpClient(clienthandler) { BaseAddress = new Uri(serveraddress) })
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
msg = client.PostAsync(endpoint, new StringContent(new JavaScriptSerializer().Serialize(data), Encoding.UTF8, "application/json")).Result;
}
var result = msg.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TR>(result);
}
AND finally the line that actually makes the call (which should not matter)
returned = CallHelper<ResultStatus<string>>.WebApiPost(serviceurl, sendFileUrl, model);
It's not clear where your web service is getting the value of PayLoad from, so it is very possible that the value has a Byte Order Mark (BOM) at its beginning. This is especially the case if you are returning the content of what was originally a Unicode encoded file.
Be aware that a BOM is NOT visible when you are viewing a string in the debugger.
On your web service, make sure that you are not returning a BOM in the value of PayLoad. Check for this byte sequence at the beginning of the string:
0xEF,0xBB,0xBF
For more information on Byte Order Mark:
https://en.wikipedia.org/wiki/Byte_order_mark

What functionality of Chrome shows a parse error as a popup?

I have no clue where this is coming from: here is it, in Java I created a servlet that runs Javascript files in Nashorn and then writes the result in a response. My Javascript code returns an object like:
function root(){
return {
"hello": 1
};
}
while my servlet returns the object (it was just a test):
Object result = invocable.invokeFunction("root", req);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
outputStreamWriter.write(result.toString());
outputStreamWriter.close();
the response raw body is:
[object Object]
and chrome will do the following:
That red popup cross even closes it on click.
Is this done by an extension that I forgot about? Or is it some kind of integration with that syntax? I've really no idea.
#gotch4
Result you're observing is expected. You're retuning string representation of JavaScript object (technically you're calling Object.protorype.toString which returns [object Object]).
I think what you really want is to invoke JSON.stringify before returning response to the browser.
Object JSON = e.eval("JSON");
Object result = invocable.invokeMethod(JSON, "stringify", invocable.invokeFunction("root", req));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
outputStreamWriter.write(result.toString());
outputStreamWriter.close();
p.s. Code should work, but I didn't test it - writing from phone.

Json: the remote server returned an error (500) internal server error

i am trying to read a web service in Json format
here is my code:
WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;
var data = wc.DownloadString(JsonUri);
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<PaymentMethod>));
var result = serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
i get an error on this line:
var data = wc.DownloadString(JsonUri);
the JsonUri is : http://avaris.kwekud.com/api/v1/items/uniqueitem/?username=joel&api_key=959dd41efd06b84ca7f10b1b12f5f3e6567c07dc&format=json
Any Help
thanks
It looks like there is a problem in the python code on the server that is returning the API. A good idea is to try to make the call from outside of your code to make sure that it is not your code. Any packet sniffing tool eg firebug in firefox will be able to tell you if the call is going wrong pr its your code being badly formed.
It looks like the API is currently broken, so you should put a try ... catch in there and handle the exception for situations like this:

Unable to get right Website response with POST?

I would like to get the response of a website that has results posted by a form. I've tried using WebClient, WebRequests, etc.
Current Code:
using (var client = new WebClient())
{
var buffer = client.UploadValues("https://secure.monroecc.edu/pls/bpr1/bwzkfcls.P_GetCrse", "POST", vals);
return Encoding.UTF8.GetString(buffer, 0, buffer.Count());
}
Also pretty sure that the current code isn't wrong it's just missing something. When I do get the response of the website it's wrong, it's the page where you would fill out the form.
If you try to GET the website it results in this error on the website itself (without posting the variables that go along with it):
VARIABLES IN FORM NOT IN PROCEDURE:
NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: TERM_IN,SEL_SUBJ,SEL_CRSE,SEL_TITLE,BEGIN_HH,BEGIN_MI,BEGIN_AP,SEL_DAY,SEL_PTRM,END_HH,END_MI,END_AP,SEL_CAMP,SEL_SCHD,SEL_SESS,SEL_INSTR,SEL_ATTR,SEL_LEVL,SEL_INSM
DAD name: bpr1
PROCEDURE : bwzkfcls.P_GetCrse
URL : http://secure.monroecc.edu:63500/pls/bpr1/bwzkfcls.P_GetCrse
PARAMETERS :
===========
Here's an image of the request being sent. (Viewing using Chrome)
I know that the website usses oracle PLSQL but again that doesn't seem to help me with retrieving the results of the search.
I posted the form using the following code:
private void Run(string[] args)
{
NameValueCollection vals = new NameValueCollection();
vals.Add("TERM_IN", "");
vals.Add("SEL_SUBJ", "");
vals.Add("SEL_CRSE", "");
vals.Add("SEL_TITLE", "");
vals.Add("BEGIN_HH", "");
vals.Add("BEGIN_MI", "");
vals.Add("BEGIN_AP", "");
vals.Add("SEL_DAY", "");
vals.Add("SEL_PTRM", "");
vals.Add("END_HH", "");
vals.Add("END_MI", "");
vals.Add("END_AP", "");
vals.Add("SEL_CAMP", "");
vals.Add("SEL_SCHD", "");
vals.Add("SEL_SESS", "");
vals.Add("SEL_INSTR", "");
vals.Add("SEL_ATTR", "");
vals.Add("SEL_LEVL", "");
vals.Add("SEL_INSM", "");
using (var client = new WebClient())
{
var buffer = client.UploadValues("https://secure.monroecc.edu/pls/bpr1/bwzkfcls.P_GetCrse", "POST", vals);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, buffer.Count()));
//Console.Read();
}
}
It returns a 200 status code and valid html indicating that the form was received properly. However, since none of the values are correct the returned page says that there is a missing form element that must be included (NAME NOT FOUND FOR PIDM: )
The parameter mismatch error you are receiving means that the parameters you are passing in are not the ones that the stored procedure expects. You'll need to get an exact list of the parameters and expected values first, then you can just plug them in and this should work. Unfortunately the page returns a 200 status code so you'll have to parse out somehow whether there was an error or not.
Use a GET request instead of a POST.
You are asking for a page that follows a form to give you a result set when it never actually receives the form variables that would make the result possible.
Your variable vals which should pass the set of variables never does.
VARIABLES IN FORM NOT IN PROCEDURE:
NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: TERM_IN,SEL_SUBJ,SEL_CRSE,SEL_TITLE,BEGIN_HH,BEGIN_MI,BEGIN_AP,SEL_DAY,SEL_PTRM,END_HH,END_MI,END_AP,SEL_CAMP,SEL_SCHD,SEL_SESS,SEL_INSTR,SEL_ATTR,SEL_LEVL,SEL_INSM
This response error says that it never received any of the variables listed. I would trace back in your code to the location were you name and assigned your list of variables to the Collection vals. Check for proper spellings and proper assignment.

How to POST JSON using Adobe Flex

I'm trying to POST some JSON data using Adobe Flex but having some problems. I'm now getting the error message "A URL must be specified with useProxy set to false", even though I do have useProxy set to false.
Update : code below is now working.
var data:Object = new Object();
data.ipaddr = ipaddr.text;
data.netmask = netmask.text;
data.gatewayip = gatewayip.text;
var jsonData:String = JSON.stringify(data);
var s:mx.rpc.http.HTTPService = new mx.rpc.http.HTTPService();
// URL needs to be specified on a separate line, call is unreliable otherwise
s.url = Utils.getBaseURL() + '/cgi-bin/setnetworksettings';
s.contentType = "application/json";
s.resultFormat = mx.rpc.http.HTTPService.RESULT_FORMAT_TEXT;
s.method = "POST";
s.useProxy = false;
s.addEventListener("result", httpResult);
s.addEventListener("fault", httpFault);
s.send(jsonData);
What do you mean by "doesn't seem to do anything"? No response from the server? Fault instead of result? Which one? Help us help you with more details, just stating it doesn't work is not enough.
First of all, be sure that your URL is correct, you should get something in the service result handler OR fault handler, anything. That should help you diagnose and fix any URL problems if any.
Then for the JSON part, you object is not a valid JSON (no escaping and : instead of =), try sending this first: {"ipaddr":"10.1.1.1"}.
From here it should be easy: as F4L stated, you can use the JSON class to encode a real object directly to JSON.
Hope that helps