TwitterAPI
久しぶりの更新はTwitterいじり。怨霊はそろそろ再開するはず。
C#から実験。
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Net; using System.Xml.Linq; using System.IO; namespace TwitterTest { class Program { static void Main(string[] args) { IEnumerable<XElement> element = null; WebClient client = new WebClient(); client.Credentials = new NetworkCredential("ID", "Password"); ServicePointManager.Expect100Continue = false;//ないとUpdateが失敗する try { UpdateStatus(client, "APIからのテスト"); } catch (Exception e) { Console.WriteLine(e.Message); } try { using (Stream stream = GetWebData(client)) { element = XElement.Parse( new StreamReader(stream).ReadToEnd()).Elements("status"); } } catch (Exception e) { Console.WriteLine(e.Message); Console.Read(); return; } var items = from s in element select new { name = s.Element("user").Element("name").Value, text = s.Element("text").Value }; foreach (var i in items) { Console.WriteLine(i.name + ":" + i.text + "\n"); } Console.Read(); } static Stream GetWebData(WebClient client) { byte[] data; string friendsURL = "http://twitter.com/statuses/friends_timeline.xml"; try { data = client.DownloadData(friendsURL); } catch (WebException e) { Console.WriteLine("Error : " + e.Message); throw new System.Exception("取得失敗", e); } return new MemoryStream(data); } static void UpdateStatus(WebClient client, string twit) { string postURL = "http://twitter.com/statuses/update.xml"; try { string convTwit = System.Web.HttpUtility.UrlEncode(twit); client.UploadString(postURL + "?status=" + convTwit, ""); } catch (WebException e) { Console.WriteLine("Error : " + e.Message); throw new System.Exception("投稿失敗", e); } } } }
LINQ to XMLを使って書いてみた。どちらかと言うと本体よりもそちらに苦戦。