2011年7月28日 星期四

Titanium HTTP Connection

//************************
//** HTTP Connection
//************************
var httpRequest = function(params) {  
    var xhr = Titanium.Network.createHTTPClient();  
    xhr.onload = function() {  
if(this.status == '200' && this.readyState==4){ 
if(params.hasOwnProperty('callback')) {  
if(typeof params.callback == 'function') {  
params.callback(this.responseText);  
}else {  
Ti.API.error('Invalid callback function');  
}  
}
}else{
Titanium.UI.createAlertDialog({title:'Error', message:'Server Busy. Try again later.'}).show();
if(params.hasOwnProperty('failcallback')){
if(typeof params.failcallback == 'function') {  
params.failcallback();  
}else {  
Ti.API.error('Invalid callback function');  
}  
}
}
    };  
    xhr.onerror = function() {  
        Titanium.UI.createAlertDialog({title:'Error', message:'Internet connection fail.'}).show();
Ti.API.error(this.status + ' - ' + this.statusText); 
if(params.hasOwnProperty('failcallback')){
if(typeof params.failcallback == 'function') {  
params.failcallback();  
}else {  
Ti.API.error('Invalid callback function');  
}  
}
    };  
    xhr.open( params.hasOwnProperty('method') ? params.method : 'GET', params.url);  
    try {  
        if(params.hasOwnProperty('username') && params.hasOwnProperty('password')) {  
            authstr = 'Basic ' +Titanium.Utils.base64encode(params.username+':'+params.password);  
            xhr.setRequestHeader('Authorization', authstr);  
        }  
    }catch(e) {  
        Ti.API.error('Error in authentication:  ' + e.message);  
    }  
if(params.hasOwnProperty('param')){
xhr.send(params.param);
}else{
xhr.send();
}
};  


 //Call it like this  
 httpRequest( {  
url:  'http://blah/blah.jsp',  
username: 'username',  
password:  'password',
param: { "param1":"value1", "param2":"value2" },
failcallback: function(){ //TODO},
callback:  function(resp) { //TODO}  
 });  


沒有留言:

張貼留言