Twitter API - Get a list of your friends in C#
I needed to call the Twitter API and get a list of friends. I
thought I could do something similar to getting a list of posts, but
alas, I had some stupid error in my linq to xml code. I futzed around
with it for days to no avail. Finally, I decided it was just easier to
iterate through the XML using an XmlNode and fill my objects that way.
Hey, it just worked. Like my previous example, this code uses C# and
is in a WCF Service. Note: As displayed, the code doesn't work, you
will have to supply a password.
[OperationContract]
public Friends[] GetFriends(string username)
{
string url = "http://twitter.com/statuses/friends.xml";
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
Friends frd;
List<Friends> lf = new List<Friends>();
request.Method = "POST";
request.Credentials = new NetworkCredential(username, password);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
reader.Close();
XmlDocument xmld = new XmlDocument();
xmld.LoadXml(responseString);
XDocument document = XDocument.Parse(responseString);
foreach(XmlNode xmln in xmld.SelectNodes("users/user"))
{
frd = new Friends();
frd.id = Convert.ToInt32(xmln["id"].InnerText);
frd.name = xmln["name"].InnerText;
frd.screen_name = xmln["screen_name"].InnerText;
lf.Add(frd);
}
return (lf.ToArray());
}
My custom object which I am streaming back looks like this:
[DataContract]
public class Friends
{
[DataMember]
public string name { get; set; }
[DataMember]
public string screen_name { get; set; }
[DataMember]
public int id { get; set; }
}
Original Url: http://morewally.com/cs/blogs/wallym/archive/2009/03/18/twitter-api-get-a-list-of-your-friends-in-c.aspx