network.request()

Type Function
Library network.*
Return value Object
Revision Current Public Release (2014.2189)
Keywords asynchronous, http, https, get, post
Sample code /CoronaSDK/SampleCode/Networking/AsynchHTTP
See also network.download()
network.upload()
network.cancel()
networkRequest

Overview

Makes an asynchronous HTTP or HTTPS request to a URL.

This function returns a handle that can be passed to network.cancel() in order to cancel the request.

 Gotchas

You cannot execute a network request during a System Suspend/Exit event. After Corona suspends, no callbacks will fire.

You can work around this by saving the request you wish to make to a file upon a System Suspend/Exit event. Then on a System Resume event, check if there is a pending request saved, and if there is, execute it.

Note that Content-Type of requests defaults to text/plain and if you are POSTing form data you'll need to set it appropriately (see HTTP POST with custom headers below).

Android

On Android, you must add the following permission to the "build.settings" file.

settings =
{
   android =
   {
      usesPermissions =
      {
         "android.permission.INTERNET",
      },
   },
}

Syntax

network.request( url, method, listener [, params] )
url (required)

String. The HTTP request URL.

method (required)

String. The HTTP method; valid values are "GET" (the default), "POST", "HEAD", "PUT", and "DELETE".

listener (required)

Listener. The listener function invoked at various phases of the HTTP operation. It is passed a networkRequest event.

The listener function can receive events of the following phases:

  • "began" - The first notification, contains the estimated size, if known.
  • "progress" - An intermediate progress notification.
  • "ended" - The final notification, when the request is finished.

By default, the listener will only receive "ended" events. If params.progress (described below) is "upload" or "download", then the listener will also receive "began" and "progress" events.

If the response body is directed to a file by using params.response (described below) and the response was successfully written to the file, then event.response will contain a table indicating the filename and baseDirectory for the output file. If the request completes, but produces an error response, then any error response body will be provided as a string in event.response instead. This behavior prevents the destination file from being written/overwritten with an error response instead of the desired payload.

params (optional)

Table. A table that specifies HTTP request or response processing options, including custom request headers or body.

  • params.headers A table specifying request header values with string keys.
  • params.body A string containing the request body, or alternatively, a table containing the filename and optionally baseDirectory for a file whose contents are to be used as the request body.
  • params.bodyType A string indicating whether a string request body is "text" or "binary", default is "text" if params.body is a string or "binary" if it is a table specifying a file.
  • params.progress A string value indicating the type of progess notifications desired, if any. One of "upload" or "download". The notification phases include the "began" and "progress" phase events for the desired direction of progress. Default is nil, indicating that only the "ended" phase event is desired.
  • params.response A table value indicating that the response body should be written to a file and specifying the filename and optionally the baseDirectory for the response file. If this value is not provided, the response body is provided as a string.
  • params.timeout A time out in seconds. Default is 30 seconds.
  • params.handleRedirects A boolean indicating whether automatic redirect handling (the default) is desired. Set this to false if you want to receive 302 responses and handle them yourself. This may be needed for certain kinds of login schemes or custom cookie handling.

Note: If a filename table is specified in params.body or in params.response, baseDirectory is an optional Constant that defaults to system.DocumentsDirectory. In the case of params.response, baseDirectory cannot be set to system.ResourceDirectory, since that directory is read-only.

Examples

For more examples, see the /CoronaSDK/SampleCode/Networking/AsynchHTTP sample project in the Corona SDK download.

For examples of canceling a request, see the documentation for network.cancel().

HTTPS/SSL

The following sample code contacts Google's encrypted search over SSL, and prints the response (in this case, the HTML source of the home page) to the Corona terminal:

local function networkListener( event )
        if ( event.isError ) then
                print( "Network error!")
        else
                print ( "RESPONSE: " .. event.response )
        end
end

-- Access Google over SSL:
network.request( "https://encrypted.google.com", "GET", networkListener )

HTTP POST with custom headers

The following code demonstrates a sending data via HTTP post, specifying custom request headers and request body.

local function networkListener( event )
        if ( event.isError ) then
                print( "Network error!")
        else
                print ( "RESPONSE: " .. event.response )
        end
end

local headers = {}

headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Language"] = "en-US"

local body = "color=red&size=small"

local params = {}
params.headers = headers
params.body = body

network.request( "http://127.0.0.1/formhandler.php", "POST", networkListener, params)

Download file with progress updates

The following code demonstrates how to download a file, with progress updates.

local function networkListener( event )
        if ( event.isError ) then
                print( "Network error!")
        elseif ( event.phase == "began" ) then
                if event.bytesEstimated <= 0 then
                        print( "Download starting, size unknown" )
                else
                        print( "Download starting, estimated size: " .. event.bytesEstimated )
                end
        elseif ( event.phase == "progress" ) then
                if event.bytesEstimated <= 0 then
                        print( "Download progress: " .. event.bytesTransferred )
                else
                        print( "Download progress: " .. event.bytesTransferred .. " of estimated: " .. event.bytesEstimated )
                end
        elseif ( event.phase == "ended" ) then
                print( "Download complete, total bytes transferred: " .. event.bytesTransferred )
        end
end

local params = {}

-- This tells network.request() that we want the 'began' and 'progress' events...
params.progress = "download"

-- This tells network.request() that we want the output to go to a file...
params.response = {
        filename = "corona.jpg",
        baseDirectory = system.DocumentsDirectory
        }

network.request( "https://www.coronalabs.com/image.jpg", "GET", networkListener,  params )

Upload text file

The following code demonstrates an HTTP post, where the request body is text that comes from a file.

Note: This example demonstrates one possible way to upload a file. Different web servers and applications support different methods of file upload. For example, some REST services support upload of a binary file in the body of a PUT request. Many web servers only allow file uploads using multipart/form-encoded (text) request bodies in a POST request. If you are going to attempt file upload, you must first understand the specific mechanism supported by the specific web server or application that you will be working with, and then you must form your request data and choose your request method appropriately.

local function networkListener( event )
        if ( event.isError ) then
                print( "Network error!")
        else
                print ( "Upload complete!" )
        end
end

local headers = {}

headers["Content-Type"] = "application/json"
headers["X-API-Key"] = "13b6ac91a2"

local params = {}
params.headers = headers

-- This tells network.request() to get the request body from a file...
params.body = {
        filename = "object.json",
        baseDirectory = system.DocumentsDirectory        
        }

network.request( "http://127.0.0.1/restapi.php", "POST", networkListener, params)