One aspect which sometimes challenges users of Corona's network library is how to properly encode URLs. Let's look at an example:
https://www.google.com/search?q=coronalabs&ie=utf-8&client=firefox-a&channel=sb
This URL can initially be dissected into the following aspects:
https://
.www.google.com
./search
.Following this, there is a series of ?
) and where each additional pair is separated by an ampersand (&
). Each actual key and associated value is separated by an equal sign (=
). In this example, we have the following
q
= coronalabs
ie
= utf-8
client
= firefox-a
channel
= sb
It's important to understand the components of URLs and the usage of the /
, .
, ?
, and &
Some basic rules for a
+
).%
).To illustrate this concept, let's consider another URL:
https://www.google.com/search?q=Corona tutorials & guides
When encoded properly, the URL looks like this:
https://www.google.com/search?q=Corona+tutorials+%26+guides
When using a URL with Corona's network library, it's your responsibility to encode it properly so that it can be safely transported across the Internet. Fortunately, a small Lua function can do the work for us:
function string.urlEncode( str ) if ( str ) then str = string.gsub( str, "\n", "\r\n" ) str = string.gsub( str, "([^%w ])", function( c ) return string.format( "%%%02X", string.byte(c) ) end ) str = string.gsub( str, " ", "+" ) end return str end
Using this function, we can then encode URLs like this:
local searchQuery = "Corona tutorials & guides" local URL = "https://google.com/q=" .. string.urlEncode( searchQuery )
Alternatively, since we added this function to Corona's
local searchQuery = "Corona tutorials & guides" local URL = "https://google.com/q=" .. searchQuery:urlEncode()
That's it! Once the URL is properly encoded, we can use it within Corona's network functions to make network requests, pass the URL to a native.newWebView(), or use it with any other API/function that requires a URL.
In summary, remember that URLs must be encoded if they contain spaces, symbols, or binary data like