Encoding URLs for Network Usage

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:

Following this, there is a series of key-value pairs which is started by a question mark (?) 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 key-value pairs:

Encoding Rules

It's important to understand the components of URLs and the usage of the symbols /, ., ?, and &. URLs can not contain spaces, nor can the keys/values contain spaces or symbols, including UTF-8 characters. In your browser, when you enter a URL which has spaces or special characters, the browser safely converts them for you. Some people test a URL in the browser, assume that it works, and attempt to use it internally with network.request() only to discover that it fails.

Some basic rules for a properly-encoded URL are:

To illustrate this concept, let's consider another URL:

http://www.google.com/search?q=Corona tutorials & guides

When encoded properly, the URL looks like this:

http://www.google.com/search?q=Corona+tutorials+%26+guides

Encoding Function

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 = "http://google.com/q=" .. string.urlEncode( searchQuery )

Alternatively, since we added this function to Corona's built-in string library, it can also be used in the colon operator syntax:

local searchQuery = "Corona tutorials & guides"
local URL = "http://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.

Conclusion

In summary, remember that URLs must be encoded if they contain spaces, symbols, or binary data like UTF-8 multi-byte characters. The handy function in this tutorial simplifies the encoding process and can help you build better network-based apps.