Search code examples
javascripttitanium

Calling RESTful webservices in Appcelerator Titanium Studio


I'm very new to Appcelerator titanium studio. Could you please help me out how to call webservice (Java Based) in Appcelerator titanium.


Solution

  • You can use Titanium.Network.HTTPClient to make RESTful calls.

    Example for GET requests

    var url = "http://www.appcelerator.com";
    var client = Ti.Network.createHTTPClient({
        // function called when the response data is available
        onload : function(e) {
            Ti.API.info("Received text: " + this.responseText);
            alert('success');
        },
        // function called when an error occurs, including a timeout
        onerror : function(e) {
            Ti.API.debug(e.error);
            alert('error');
        },
        timeout : 5000  // in milliseconds
    });
    // Prepare the connection.
    client.open("GET", url);
    // Send the request.
    client.send();
    

    Example for POST requests

    var xhr = Ti.Network.createHTTPClient();
    xhr.onload = function(e) {
        //handle response, which at minimum will be an HTTP status code
    };
    xhr.open('POST','http://www.myblog.com/post.php');
    xhr.send({
        title:'My awesome blog',
        body:'Today I met Susy at the laundromat.  Best day EVAR\!'
    });
    

    It supports the verbs GET, POST, DELETE, PUT, PATCH