Is there a library for converting strings in as3 into the application/x-www-form-urlencoded format?
Specifically, I am looking for the same functionality as the java URLEncoder http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
Unfortunately, as3's escape and encodeURIComponent functions don't do it. For example, lots of %20s instead of +'s.
For encoding URL parameters, both %20 and + are valid representations of the space character, and both URLVariables.toString() and URLUtil.objectToString() emit compliant application/x-www-form-urlencoded data using the former (per ECMA-262). The encodeURI(), encodeURIComponent() and escape() functions all operate similarly. From the AS3 docs:
flash.net.URLVariables.toString()
Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded.
mx.utils.URLUtil.objectToString()
You typically use this method to convert an ActionScript object to a String that you then append to the end of a URL. By default, invalid URL characters are URL-encoded (converted to the %XX format).
Encodes a string into a valid URI component. Converts a substring of a URI into a string in which all characters are encoded as UTF-8 escape sequences unless a character belongs to a very small group of basic characters.
Converts the parameter to a string and encodes it in a URL-encoded format, where most nonalphanumeric characters are replaced with % hexadecimal sequences.
Here's an example showing the usage and output of all four approaches:
import mx.utils.URLUtil;
private function test():void
{
var url:String = "http://www.google.com/search?";
var s:String = "here is my search query";
var variables:URLVariables = new URLVariables();
variables.q = s;
var o:Object = new Object();
o.q = s;
trace(url + "q=" + encodeURIComponent(s));
trace(url + variables.toString());
trace(url + "q=" + escape(s));
trace(url + URLUtil.objectToString(o));
}
All four emit the same result (just as JavaScript's own encodeURIComponent() does):
// http://www.google.com/search?q=here%20is%20my%20search%20query
I agree the plus signs are easier on the eyes, though! To swap them out manually:
trace(url + "q=" + escape(s).split("%20").join("+"));
But if there's an ActionScript class or top-level function that uses plus signs instead of hex sequences for spaces, I'm not aware of it.