I have received a couple requests for an example of networking, so I put something very basic together to show some simple functionality.
//location of file to be downloaded
//the real URL should be a valid domain
var src = "http://localhost/sample_file.txt";
//destination where download will be stored
//here its the same file name as the downloaded file, stored in p-storage
var dest = "file:///required/" + PersistentStorageManager.contentId + src.substring(src.lastIndexOf("/"),src.length);
//timeout in seconds...use -1 for no timeout
var timeout = 30;
//size of download - use for percent download complete
var downloadSize = 5000;
//network object - referenced in OnDownloadStateChange
var httpClient;
//confirm user has network connection
if (Player.capabilities.network.connected == true)
{
try
{
httpClient = Network.createHTTPClient(src, Network.HTTP_GET, timeout);
httpClient.downloadFileLocation = dest;
//set a callback to track progress of download
httpClient.onStateChange = OnDownloadStateChange;
httpClient.send();
}
catch(ex)
{
TraceError("Download FAILED", ex, arguments.callee);
}
}
else
{
TraceInfo("Network connection not available",arguments.callee);
}
function OnDownloadStateChange(state)
{
switch (state)
{
case httpClient.STATE_RESPONSEPROGRESS:
/*
Download is still occuring
If you know your download size, you can look at
httpClient.dataDownloaded to determine percent progress
*/
if (downloadSize)
{
var percentComplete = Math.floor(100 * httpClient.dataDownloaded / downloadSize);
}
break;
case httpClient.STATE_COMPLETED:
/*
Do something with file that is now at downloadLocation
*/
TraceInfo("STATE_COMPLETED",arguments.callee);
httpClient = null; //destroy client to avoid closure issue
break;
case httpClient.STATE_ERROR:
/*
Download failed, handle accordingly
*/
TraceInfo("STATE_ERROR",arguments.callee);
httpClient = null; //destroy client to avoid closure issue
break;
case httpClient.STATE_ABORT:
/*
Download aborted, handle accordingly
*/
TraceInfo("STATE_ABORT",arguments.callee);
httpClient = null; //destroy client to avoid closure issue
break;
}
}
Or, alternatively if you are only expecting a text string as a response from the server, don't set downloadFileLocation and on STATE_COMPLETED, use httpClient.getResponseString() to get that text string