This post was originally published at Tutorial: 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:

This URL can be dissected into the following aspects:

  • The schema, in this case https://.
  • The domain name, in this case
  • The script to run, in this case /search.

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:

  • q=coronaSDK
  • ie=utf-8
  • client=firefox-a
  • channel=sb

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:

  • Spaces are converted to plus signs (+).
  • Other symbols must be converted to a hexadecimal value that is prefixed by a percent sign (%).

Let’s consider another URL:

When encoded properly, the URL looks like this:

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 function can do the work for us. There are several available on the Internet, but here’s a simple Lua function:

We could then construct our URLs like this:

For usage convenience, note that we’ve added this function to Corona’s built-in string library. Thus, when we include this function in our code, it can be used like any other string-based function:

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 UTF-8 multi-byte characters. The handy function in this tutorial simplifies the encoding process and can help you build better network-based apps.


This post was originally published at Tutorial: Encoding URLs for Network Usage