Technology Article

About Net Loading

Explains the use of the Loader class and using HTTP GET and POST in Luster.

GET Data

Luster has the capability to GET data to an HTTP server. This means you can pass data to the server using the standard ? operator within the URL. You can also download files by using HTTP GET without passing any data to the server. Let's assume that we want to download the home page for Luster3D.

local url = luster.net.URL("http://luster3d.com/index.php")
local request = luster.net.URLRequest(url)
self.loader = luster.net.Loader()
self.loader:addEventListener(luster.net.Loader.COMPLETE, function(myLoader)
	trace(myLoader.data)
end)
self.loader:load(request)

The first step to using the luster.net.Loader class is to construct a URL object. This points to the remote resource you want to access. In this case we point it to the index.php file for luster3d.com.

The next step is to construct a URLRequest object. This wraps the URL and represents a request to the server. In this case, we don't set any other variables on the object, but in the future we will use other properties of URLRequest to customize the data sent to the server.

We can finally construct the loader object. We listen for the COMPLETE event, because all HTTP requests are asynchronous. When the data has been loaded we simply trace it out to the console. Running this code should output the HTML code for the luster3d home page.

POST Data

The luster.net.Loader class also has the ability to POST data to servers and receive the responses. This is great for accessing external APIs (such as REST services available from Yahoo or Google). In this case we'll access Yahoo's Placemaker service.

local request = luster.net.URLRequest("http://wherein.yahooapis.com/v1/document")
request.method = luster.net.URLRequest.Method.POST
request.postData = {documentType = "text/plain", documentContent = "", appid = ""}
self.loader = luster.net.Loader()
self.loader:addEventListener(luster.net.Loader.COMPLETE, function(myLoader)
	trace(myLoader.data)
end)
self.loader:load(request)

We use the same classes to POST data. Here we construct the URLRequest directly with the URL string (instead of constructing the URL object). We set the method of the request to POST and then set the post data. The post data is set by giving the property a table of key-value pairs. The key-value pairs will be encoded and sent to the server as if they were sent in from an HTML form.

After constructing the request, we use the Loader object just as we did with GET. We just output the response from the server to the console. Of course, in a real application you can take the data (such as an XML response) and parse it for information.