The correct way to make a Twitter Request
Many of you might be making a JSON request to twitter in the following format:
xhr.open('GET','http://'+username.value+':'+password.value+'@api.twitter.com/1/statuses/user_timeline/' + username.value + '.json?count=200');
This is incorrect because Twitter now requires base64 or OAuth authentication for this request.
The response from this request will only return public information. Information like "favorited" will not be available since you haven't truly authenticated (it will always show false even if it is true ex. favorited: false) .
Titianium offers a method for base64 Authentication. (The correct method for authentication to twitter).
xhr.setRequestHeader('Authorization','Basic '+Ti.Utils.base64encode(username.value+':'+password.value));
You can set this right after you open an connection and it will authenticate your request properly. You should now receive the correct JSON response from twitter.
Below is a full example of how to make this request correctly.
Note: assume the username and password variables are text field objects that the user has typed their information into
var data = {
stream: []
};
function getStream() {
var xhr = Titanium.Network.createHTTPClient();
//ERROR
xhr.onerror = function(e) {
alert("ERROR " + e.error);
};
//SUCCESS
xhr.onload = function() {
var resp = eval(this.responseText);
//Add Twitter Data to Array
for(var i = 0, l = resp.length; i < l; i++) {
data.stream.push(resp[i]);
}
};
//OPEN
xhr.open('GET','http://api.twitter.com/1/statuses/user_timeline/' + username.value + '.json?count=200');
xhr.setRequestHeader('Authorization','Basic '+Ti.Utils.base64encode(username.value+':'+password.value));
//SEND
xhr.send();
};
Special thanks to Jeffery Haynie for finding the answer to this!
1 Answer
-
Accepted Answer
question is the answer.