This feature allows you to make asynchronous HTTP and HTTPS/SSL calls, using any valid HTTP method ("GET", "POST", etc.), as well as adding custom header and body content. Your Corona program does not need to stop while waiting for a response from the server, which is returned in an event and accessed through event listeners.
In addition, you can choose to download the network response to a specified file, rather than loading it into memory. This is useful when the response is a larger documents or an image.
Two new sample projects illustrate the uses of this feature: "Network/AsynchHTTP" and "Network/AsynchImageDownload".
Note: in a prerelease version of this feature, you had to explicitly require the internal "network" library in your code, but this library is now included automatically. The examples below are modified accordingly.
To send a request to a server, specify a URL, a method, and a listener for the result.
The default method is "GET", if no method is specified.
The resulting event has the following properties:
Here is a working example, which will contact Google's encrypted search over SSL, and print the response (in this case, the 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 )
In some cases, you may wish to specify additional headers, or include a body in the request. Both of these can be accomplished with the optional params table, which may contain any of the following:
params.headers -- A table specifying header values with string keys.
params.body - A string containing the HTTP body.
Example of headers table (these are appended to whatever headers iOS sends already)
headers = {} headers["Content-Type"] = "application/json" headers["Accept-Language"] = "en-US" headers.body = "This is an example request body."
This API is similar to the one above, except that it downloads the response to a local filename and file path that you specify, rather than cacheing it in memory. This is recommended for large responses (for example, long XML documents), and can also be used for downloading remote images.
The default method is "GET", if no method is specified. The optional baseDir parameter can be either system.DocumentsDirectory (the default) or system.TemporaryDirectory.
The resulting event has the following properties:
The following example downloads a remote image to a local file copy, and then displays it on the screen:
local function networkListener( event ) if ( event.isError ) then print ( "Network error - download failed" ) else myImage = display.newImage( "helloCopy.png", system.TemporaryDirectory, 60, 40 ) myImage.alpha = 0 transition.to( myImage, { alpha = 1.0 } ) end print ( "RESPONSE: " .. event.response ) end network.download( "http://developer.anscamobile.com/demo/hello.png", "GET", networkListener, "helloCopy.png", system.TemporaryDirectory )
This API is a convenience method that accesses a remote image and returns it as a visible display object. It is similar to the network.download() API (in fact, it uses it behind the scenes), but it simplifies coding.
The default method is "GET", if no method is specified. The optional baseDir parameter can be either system.DocumentsDirectory (the default) or system.TemporaryDirectory.
The resulting event has the following properties:
The following example downloads a remote image to a local file copy, and then displays it on the screen:
llocal function networkListener( event ) if ( event.isError ) then print ( "Network error - download failed" ) else event.target.alpha = 0 transition.to( event.target, { alpha = 1.0 } ) end print ( "RESPONSE: " .. event.response ) end display.loadRemoteImage( "http://developer.anscamobile.com/demo/hello.png", "GET", networkListener, "helloCopy.png", system.TemporaryDirectory, 60, 280 )
Is it possible to have further details on this?
Is this "Lua Socket" integrated and made async or a new module ?
If it's a new module, can we still use Lua Socket for more functionalities (like UDP etc ?). How do you require Lua Socket now ? etc.
Thanks.
This is a new module and you can still use LuaSockets. You find more information about LuaSockets here: http://developer.anscamobile.com/content/network
whenever I try and launch I always receive the error:
ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
stack traceback:
[C]: ?
[C]: in function 'insert'
I am new to lua so I dont know what the problem is
I have been able to use your sample code almost verbatim for display.loadRemoteImage to successfully load an image. However if I say:
1 2 3 4 5 | local thisItem = display.newGroup() local testImage =nil; testImage= display.loadRemoteImage(imageURL, "GET", networkListener, id ..".jpg", system.TemporaryDirectory, 0, 0) thisItem:insert(testImage) |
I have omitted the network Listener in my sample code as I have not made any changes to it.
I recieve the following error at runtime: ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
stack traceback:
[C]: ?
[C]: in function 'insert'
I am fairly new to lua so I am assuming I am doing something wrong, or don't have complete understanding about what can and cannot be added to a display group. Can someone shed some light on this?
Thanks
Joe
@joe,
The example for loadRemoteImage was incorrect when it showed returning a pointer to the downloaded display object. You can access "testImage" in the listener function by the following:
testImage = event.target
To make your code work you will need to move the creation of the "thisItem" group in the Listener or before it.
I've corrected the example code on this page to show no value returned from loadRemoteImage.
I have the same question as steve918. Does this work on Android? Also does it work in the Windows version of the SDK/simulator?
I tried the supposedly "working" example code at the top of this page to connect to google and display a response and it does nothing for me. I added a print ( "network listener fired!" ) line to the top of the networkListener function and it never printed anything. I also tried it with just http instead of https and it didn't work.
I have build 2011.288 (Jan 28 2011) for Windows and I get nothing out of network.request even in the simulator. I have Windows XP Pro Version 2002 SP3.
I do have the correct build.settings file per specification at http://developer.anscamobile.com/content/network
@vkrist, This feature has not been implemented in the Windows Simulator or Android.
@Tom,
Thanks for your response. Is there any way that I can pass any other information to the network listener? such as the pointer to a display group?
I am working with the list view sample that someone had posted: http://developer.anscamobile.com/content/list-view-1 and am losing the reference to the proper row if I declare the pointer as a global variable inside the file as the individual rows (display groups) are built iteratively. (Sorry if my syntax names aren't correct) Not sure how to identify the proper row to add the image to.
Any guidance would be appreciated.
Thanks
Joe
You can't pass anything to the listener, but you can retrieve the file name of the image that was retrieved in the listener event. You could use this to look up the row in a table that you created. Another solution is to set a local variable with the next row number (group) and use this in the Listener event.
As a side note, whenever you create display objects (images, graphics, groups), you can always add your own custom parameter to the object.
For example:
1 2 3 | local myGroup = display.newGroup() myGroup.nextRow = 5 -- custom parameter myGroup:insert( myImage ) |
I hope that helps.
-Tom
Thanks for the clarification Tom. Unfortunately, this is a show stopper for me due to our corporate security policies. Please advise when or IF you expect https support for Android and Windows Simulator.
BTW I tried using LuaSockets but https doesn't seem to work in my tests and your docs seems to support my results. I refer to http://developer.anscamobile.com/content/network where among other statements Walter (your staff) indicates the new Asynch network API's will get us SSL but then you indicated it is only for iOS.
I ran the AsyncHTTPRequest Sample in the windows corona simulator. The code ran without crashing and printing a stack trace, but the network event never seems to fire. I.e. it just says "(waiting for response)" forever and never gets the response.
Any ideas as to why this happens? And how to fix it?
EDIT: I see, that this feature has not yet been implemented for the windows android simulator
So what would you say is a "large" XML file? What would the line count get to before you recommended saving the file locally, and not in program memory?
Thanks!
Does this work for android in the Mac Simulator??
Because the new build says
"Bug Fixes
Android: network.request now working. Fixed crash in AsyncHttp and any code that uses network.request. Prevent nullpointerexception on param conversion for async network requests.(333) - case 3063"
Is there a way to get an http response code in the network listener?
I download a json file through network.download. It works but if the file do not exist on the remote server, I don't get an error, I download and write an apache error log in HTML saying the file could not be found.
Is there a way to manage error with network.download ?
Is this working on Android now too?