I am trying to upload a photo from an Adobe AIR application to yfrog's api, http://code.google.com/p/imageshackapi/wiki/YFROGuploadAndPost. I have the following code:
public function upload(file:File, msg:String, username:String, password:String):void {
var vars:URLVariables = new URLVariables();
vars["username"] = username;
vars["password"] = password;
vars["public"] = "yes";
vars["key"] = API_KEY; //API_KEY is a constant string that holds my developer key
vars["message"] = msg;
var request:URLRequest = new URLRequest("http://yfrog.com/api/uploadAndPost");
request.method = URLRequestMethod.POST;
request.contentType = "multipart/form-data";
request.data = vars;
file.upload(request, "media");
}
When I run this code, yfrog returns 404 status. This seems to only happen if I do a media file upload with the api. If I use a "url" upload to the same api url - everything works. Has anyone else gotten a "media" file upload to work? If so, how would you change the code?
Looks like that API has been replaced as of today with the OAuth Echo method
http://code.google.com/p/imageshackapi/wiki/TwitterAuthentication
Related
I've asked my client to share his database login and password but he can't give me full access to his database (security reason I suppose).
He told me to use a REST/JSON service that allows to post the data via this url with a specific key that allows him to identify all the datas coming from my app.
Here's what I did :
var urlRequest:URLRequest = new URLRequest("the_url_using JSON service");
urlRequest.method = URLRequestMethod.POST;
var urlvars: URLVariables = new URLVariables;
urlvars.observer_name = "Test Coco";
urlvars.observation_number = "5433";
trace("urlvars = "+urlvars);
urlRequest.data = urlvars;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(urlRequest);
It's working, as it's sending the data, but the data format seems to be incorrect..
the url returns this error : "Observer name is Missing"
And the "trace (urlvars)" output :
urlvars = observer%5Fname=Test%20Coco&observation%5Fnumber=5433
So I think the problem come from the special character or something like that (as you can "observer_name" results by "observer%5Fname" and we can see a lot of %5")
Any idea how can I solve this ?
JSON string is a string representation of a generic object. Basically you go:
var anObject:Object =
{
"observer_name": "Test Coco",
"observation_number": 5433
};
or you can construct it
var anObject:Object = new Object;
anObject['observer_name'] = "Test Coco";
anObject['observation_number'] = 5433;
and then you convert it to String and attach to request
var jsonString:String = JSON.stringify(anObject);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = jsonString;
Read more about it: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html
Keep in mind that I don't know the specifics of that REST server of yours and the code above just might not work as it is. I only explain how to send a JSON string as a POST request.
When uploading a file from adobe AIR to a backbone server, the response returned is not anyway accessible when using file.upload(request) function, while i can see json response in fiddler(web debugger and in task manager), also it was working fine when using URLLoader.load() instead of file.upload()
var url = "api url of backbone server ";
request = null;
file = null;
request = new air.URLRequest(url);
request.useCache = false;
var authorization = new air.URLRequestHeader("Authorization", "Bearer "+accessToken);
var contentType = new air.URLRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
var Accept = new air.URLRequestHeader("Accept", "application/json;charset=UTF-8");
request.requestHeaders.push(authorization);
request.requestHeaders.push(contentType);
request.requestHeaders.push(Accept);
file = new air.File(path);
pathNative = file.nativePath;
var directory = getDirectoryFromPath(pathNative);
params = new air.URLVariables();
params.parent_id = directory.directory_id;
params.name = file.name;
request.data = params;
request.method = air.URLRequestMethod.POST;
request.contentType = 'multipart/form-data, boundary='+boundary;
var file = new air.File(path);
file.upload(request);
file.addEventListener(air.Event.COMPLETE, function(e){
air.Introspector.Console.log(file);
air.Introspector.Console.log(e);
air.Introspector.Console.log(e.target.data);
});
This is the console for complete event as you can see returned data is null.
see console
while in fiddler shows that json is returned.
see fiddler
Seems like it's a known issue on iOS? Are you trying to do this from iOS?
https://forums.adobe.com/thread/1720117?start=0&tstart=0
I ran into the same problem. Instead of using air.Event.COMPLETE, try to use air.DataEvent.UPLOAD_COMPLETE_DATA:
file.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, function(e){
air.Introspector.Console.log(e.data);
});
This question already has answers here:
URLRequest/URLLoader auto-converting POST request to GET
(2 answers)
Closed 7 years ago.
i have this file that makes an API request somewhere to retrieve JSON data.
The request needs to have 2 custom headers. I've read that custom headers require the request to be a POST.
I've read all the previous questions here and also on other sites, i think the code shows it pretty well... The "funny" part is that at some point i created a logger (environment: Tomcat) to see why it wasn't loading, and apparently the request i'm sending is a GET even if i've specified for it to be a POST...
Code
var url:String = "your_url_here";
var headers:Array = [
new URLRequestHeader("user-id","your_user-id"),
new URLRequestHeader("custom-auth","your_custom_auth_code"),
new URLRequestHeader("Accept","application/json")
];
var request:URLRequest = new URLRequest();
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.url = url;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
loader.load(request);
private function handleError(e:IOErrorEvent):void{
sometextcontainer.txt01.text = e.toString();
}
private function decodeJSON(e:Event) {
var Info:Object = JSON.parse(e.target.data);
// text fillers
}
The error: #2032 STREAM ERROR but i was 100% sure about the URL being correct, so i made a logger to actually see what was happening on the other side and surprise surprise... The request appears to be a GET!
What did i do wrong? Ideas?
Note1: i don't have sandbox security problems as i already placed Global exceptions;
Note2: i tried the request in REST with the custom headers (as POST) and it works (and the logger says i actually made a POST...)
Thanks for your kind help! :)
That made the trick.
I'm adding the code in order to make everyone understand it better and quicker. Basically, i added the following:
var datareq:URLVariables = new URLVariables();
datareq.dummyTest = "true";
request.data = datareq;`
So now it looks like:
var request:URLRequest = new URLRequest();
var datareq:URLVariables = new URLVariables();
datareq.dummyTest = "true";
request.data = datareq;
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.url = url;
Thanks for the help.
I'm trying to get a simple app working from within Flash to see a users tweets.
I 'believe' I have correctly gotten the access token.
var bearerToken:String;
var consumerKey:String = <CONSUMER_KEY>;
var consumerSecret:String = <CONSUMER_SECRET>;
//encode key and secret according to twitter's website
var bearerTokenCredentials = Base64.encode(consumerKey + ':' + consumerSecret);
//setup my request variables, according to twitters dev info, use client_credentials for grant_type
var requestVars:URLVariables = new URLVariables();
requestVars.grant_type = 'client_credentials';
//according to twitter, the url to use for application-only authenticaton
var url:String = 'https://api.twitter.com/oauth2/token';
//setup a URLRequest object with the proper headers, according to twitter, need the Authorization header to be 'Basic <encoded key/secret>' and the proper Content-Type header
var request:URLRequest = new URLRequest(url);
request.requestHeaders = [new URLRequestHeader('Authorization', 'Basic ' + bearerTokenCredentials),
new URLRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')];
request.method = URLRequestMethod.POST;
request.data = requestVars;
//send the request to authenticate
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onBearerTokenRequest);
urlLoader.load(request);
function onBearerTokenRequest(e:Event):void
{
trace('onRequestComplete');
//this works and i get a token
bearerToken = JSON.decode(e.currentTarget.data).access_token;
//HERE IS WHERE I CAN'T FIGURE OUT WHAT'S WRONG
var url:String = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
var urlVariables = new URLVariables();
urlVariables.screen_name = 'rivercitygraphx';
urlVariables.count = 2;
var request:URLRequest = new URLRequest(url);
request.method = "GET";
request.requestHeaders = [new URLRequestHeader('Authorization', 'Bearer ' + bearerToken)];
request.data = urlVariables;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onTimelineRequestComplete);
urlLoader.load(request);
}
function onTimelineRequestComplete(e:Event):void
{
trace('onTimelineRequestComplete');
}
I get the token back properly (well I assume so since I get a long string).
But when I try to make the request for the user timeline I get an ioError Error opening URL 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen%5Fname=kamcknig&count=2' which makes me think the URL is malformed, but according to everytihng I see, it seems correct.
Also, right now I'm just testing this within the Flash IDE.
Can anyone help??
I have since used the POSTMAN extension in Chrome and entered the url, and the Authorization header with the bearer token that I received and the request worked within POSTMAN!
So the only thing that i can think is it's the Flash IDE. Anyone have any ideas why that might be or if that might actually even be the problem?
OK after all my research it looks like this is impossible.
I have found a library that uses a socket connection that can do what I want, but the filesize is far too large. The Socket class in AS3 is not a secure socket so I can't use it. And the SecureSocket class can't be used either since I am limited to Flash Player 10 and earlier.
So as far as I'm concerned, this is impossible.
I need to upload an xml file to the server with a IOS application developed in Flex. I am getting a
Flex File I/O Error #2038. It is a very generic i/o error and doesn't provide any further details that would help me track down the root problem. Everything goes well on Windows when debugging the App it only happens when I debug the App on the apple Air tablet.
I ran into this post https://www.catalysts.cc/en/wissenswertes/flex-file-io-error-2038-on-mac-clients/ which looks like something similar but to be honest I wasn't able to use this information. It seems that my tablet may be corrupting the URL. I haven't made any traffic monitoring but I can swear the call is not even made.
Here is the code:
var f:File = new File('app-storage:/Output_WithAllInfo.xml');
var request:URLRequest = new URLRequest();
request.url = http://myHost/JsonServer/?country=DE&language=deu&operationtype=custom&select=[{\"item\":\"*\"}]&sessionid="+sessionId+"&custom=[{\"package\":\"eu.app\",\"name\":\"syncInUpload\",\"data\":{\"nxpkeyProcessId\":"+processId+",\"nxpkeyProcessDefinitionId\":null,\"xml\":null}}]";
request.method = URLRequestMethod.POST;
f.upload(request,"xml", false);
The request parameters are:
authenticate:true
cacheResponse:true
contentType:null
data:null
digest:null
followRedirects:true
idleTimeout:0
manageCookies:true
method:"POST"
requestHeaders:[] length:0
url:http://domain/JsonServer/?country=DE&language=deu&operationtype=custom&select=[{"item":"*"}]&sessionid=b9f33c5e-0445-49d3-ab5c-a335229596cf&custom=[{"package":"eu.app","name":"syncInUpload","data":{"nxpkeyProcessId":606,"nxpkeyProcessDefinitionId":null,"xml":null}}]
useCache:true
userAgent:"Mozilla/5.0 (iOS; U; de) AppleWebKit/533.19.4 (KHTML, like Gecko) AdobeAIR/3.7"
And I get the error:
Error #2038: File I/O Error. URL: http://domain/JsonServer/?country=DE&language=deu&operationtype=custom&select=[{"item":"*"}]&sessionid=b9f33c5e-0445-49d3-ab5c-a335229596cf&custom=[{"package":"eu.app","name":"syncInUpload","data":{"nxpkeyProcessId":606,"nxpkeyProcessDefinitionId":null,"xml":null}}]
I really need help here...
Thanks
Should I try something like this:
var req:URLRequest=new URLRequest("url");
req.method=URLRequestMethod.POST;
var postData:URLVariables=new URLVariables();
postData.country= 'DE';
postData.language='deu';
postData.operationtype= 'custom';select='[{\"item\":\"*\"}]';
sessionid=e.session;
custom='[{\"package\":\"eu.app\",\"name\":\"syncInUpload\",\"data\":\"nxpkeyProcessId\":606,\"nxpkeyProcessDefinitionId\":null,\"xml\":null}}];
req.data = postData;
var loader:URLLoader = new URLLoader();
loader.dataFormat=URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE,
loader_complete);
loader.load(req);
Try using the UrlVariables class Documentation
The solution for my problem was encoding the URL I changed the code to:
var f:File = new File('app-storage:/Output_WithAllInfo.xml');
var request:URLRequest = new URLRequest();
var jsonParams:String = "/JsonServer/?country="+e.country+"&language="+e.lang+"&operationtype=custom&select=[{\"item\":\"*\"}]&sessionid="+e.sessionId+"&custom=[{\"package\":\"eu.app\",\"name\":\"syncInUpload\",\"data\":{\"nxpkeyProcessId\":"+e.processId+",\"nxpkeyProcessDefinitionId\":null,\"xml\":null}}]";
request.url = GlobalCGStaticVars.ipAddressJsonCalls+htmlencodeSpecial(jsonParams);
request.url = 'http://myHost'+htmlencodeSpecial(jsonParams);
request.method = URLRequestMethod.POST;
f.upload(request,"xml", false);
protected function htmlencodeSpecial(str:String):String
{
var result:String = '';
for (var i:int=0 ; i< str.length; i++)
{
var unicode:String = '';
if(str.charAt(i)=='{')
unicode = '%7B';
else if(str.charAt(i)=='[')
unicode = '%5B';
else if(str.charAt(i)==':')
unicode = '%3A';
else if(str.charAt(i)==']')
unicode = '%5D';
else if(str.charAt(i)=='}')
unicode = '%7D';
else if(str.charAt(i)=='"')
unicode = '%22';
else
unicode = str.charAt(i);
result += unicode;
}
return result;
}