LiveCode LessonsHow To - Step-By-Step Guides To Tasks In LiveCode TSNetHow to use tsNetGetSync to retrieve data from a web site

How to use tsNetGetSync to retrieve data from a web site


This lesson is designed to show how the tsNet external can be used to retrieve data from a website.  The example code in this lesson retrieves and displays the current exchange rate between the Australian and US dollar.

To achieve this goal, we use the tsNetGetSync function from the tsNet external library.

Lay out the Stack

Create a new stack then drag a button and a field onto it.

Set the name of the field to "Output".

Save this stack.

Create the Script

Edit the script of the button that you placed on the stack by right clicking on the button and selecting "edit script".

Add the following code.

on mouseUp pButtonNumber
   -- The following line is the call to tsNetGetSync
   put tsNetGetSync("", tHeaders, tRecvHeaders, tResult, tBytes) into tData
   -- tResult will be 200 (the HTTP response code for a successful transfer) if
   -- tsNetGetSync was able to retrieve the data
   -- If this is not the case, we will inform the user
   if tResult is not 200 then 
      answer "Could not retrieve data" 
      -- The retrieved data is in JSON format, convert to a normal LiveCode array
      put JSONtoArray(tData) into tArray
      -- Display the appropriate currency rate in the "Output" field
      put "$1.00 USD dollar is currently $" & tArray["rates"]["AUD"] && "AUD dollars" into field "Output"
   end if 
end mouseUp

More information

The code above shows a very simple example of how to use tsNetGetSync to retrieve data.  There are additional parameters that can be used with the tsNetGetSync function that allow more specific configuration and provide more information on the response that is returned from the web server.  However, as can be seen above, these additional parameters are often not necessary when retrieving data from a website.

In particular, the tHeaders variable can be used to control what HTTP headers are sent with the HTTP GET request.  The tRecvHeaders variable contains the HTTP headers returned from the web server and the tBytes variable stores the number of bytes of data that has been returned.

More information about these additional parameters can be found in the LiveCode dictionary.



Switch to Run mode and click the button.


Add your comment

E-Mail me when someone replies to this comment