User:Lou Netizen/HTTP GET Example (GridSurvey)

From Second Life Wiki
Jump to navigation Jump to search

This script is a simple example of using LSL's HTTP functionality to send a GET request to an offworld Web server. It is based on the TimeAPI_Clock_Script by Ryan R. Elite (Elite Runner). However, since the endpoint that script used shut down sometime in 2017, I reworked slightly to make a working example for scripters unfamiliar with using HTTP with LSL.

This script uses LSL's HTTP request function to get the name of a random online region on the Second Life Grid from Tyche Shepherd's GridSurvey. This API was chosen because it returns results as simple text that don't have to be "unpacked" from formats like HTML, XML, or JSON. Each time a user touches the object containing the script, it retrieves and displays the name of a new randomly selected online region.

Submitted for the LSL Script Library.

Script

key reqKey;
 
default
{
    state_entry(){
        llSetText("Touch to see if a random region is online",<0,1,0>,1.0);
    }
 
    http_response(key req_id, integer status, list metadata, string body)
    {
        if (req_id == reqKey)
        {
            if (status == 200) {
                llSetText("GridSurvey says the region '" + body + "' is online!\nTouch to see another",<1,1,1>,1.0);
            } else {
                llSetText("ERROR",<1,0,0>,1.0);
            }
        }
    }
 
    touch_start(integer n)
    {
        reqKey = llHTTPRequest("http://api.gridsurvey.com/simquery.php?region=FETCH_RANDOM_ONLINE_REGION_FROM_DATABASE", [HTTP_METHOD,"GET"],"");
    }
}

This script in the public domain. You can contribute to it and use it in your projects.