.NET調用新浪微博開放平臺接口的代碼示例
博客園在新浪微博上開了官方微博(http://t.sina.com.cn/cnblogs),為了方便一些信息的更新,比如IT新聞,我們使用了新浪微博開放平臺接口。
在這篇文章中,我們將和大家分享如何通過.NET(C#)調用新浪微博開放平臺接口。
使用新浪微博開放平臺接口,需要先申請一帳號,申請方法:給 @微博開放平臺 發送私信,或者給open_sina_mblog@vip.sina.com發郵件,附上您的email,微博個人主頁,電話,和簡單介紹。
我們發了申請郵件后,不到1小時就收到了申請通過的郵件。然后進入新浪微博開放平臺查看相關文檔,在文檔中(使用Basic Auth進行用戶驗證)發現新浪微博開發團隊推薦了園子里的Q.Lee.lulu寫的一篇博文:訪問需要HTTP Basic Authentication認證的資源的各種語言的實現。這篇文章成為了我們的重要參考,但該文只是針對“GET”請求的情況,而新浪微博開放平臺接口要求HTTP請求方式為“POST”,我們又參考了園子里的烏生魚湯寫的另一篇博文: 使用HttpWebRequest發送自定義POST請求。在這里感謝兩位園友的分享!
接下來,我們開始.NET調用新浪微博開放平臺接口之旅。
1. 首先我們要獲取一個App Key,在新浪微博開放平臺的“我的應用”中創建一個應用,就會生成App Key,假設是123456。
2. 在新浪微博API文檔中找到你想調用的API,這里我們假定調用發表微博的API-statuses/update,url是http://api.t.sina.com.cn/statuses/update.json,POST的參數:source=appkey&status=微博內容。其中appkey就是之前獲取的App Key。
3. 準備數據
1) 準備用戶驗證數據:
- string username = "t@cnblogs.com";
- string password = "cnblogs.com";
- string usernamePassword = username + ":" + password;
username是你的微博登錄用戶名,password是你的博客密碼。
2) 準備調用的URL及需要POST的數據:
- string url = "http://api.t.sina.com.cn/statuses/update.json";
- string news_title = "VS2010網劇合集:講述程序員的愛情故事";
- int news_id = 62747;
- string t_news = string.Format("{0},http://news.cnblogs.com/n/{1}/", news_title, news_id );
- string data = "source=123456&status=" + System.Web.HttpUtility.UrlEncode(t_news);
4. 準備用于發起請求的HttpWebRequest對象:
- System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
- System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;
5. 準備用于用戶驗證的憑據:
- System.Net.CredentialCache myCache = new System.Net.CredentialCache();
- myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(username, password));
- httpRequest.Credentials = myCache;
- httpRequest.Headers.Add("Authorization", "Basic " +
- Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(usernamePassword)));
6. 發起POST請求:
- httpRequest.Method = "POST";
- httpRequest.ContentType = "application/x-www-form-urlencoded";
- System.Text.Encoding encoding = System.Text.Encoding.ASCII;
- byte[] bytesToPost = encoding.GetBytes(data);
- httpRequest.ContentLength = bytesToPost.Length;
- System.IO.Stream requestStream = httpRequest.GetRequestStream();
- requestStream.Write(bytesToPost, 0, bytesToPost.Length);
- requestStream.Close();
上述代碼成功執行后,就會把內容發到了你的微博上了。
7. 獲取服務端的響應內容:
- System.Net.WebResponse wr = httpRequest.GetResponse();
- System.IO.Stream receiveStream = wr.GetResponseStream();
- using (System.IO.StreamReader reader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
- {
- string responseContent = reader.ReadToEnd();
- }
好了,.NET調用新浪微博開放平臺接口之旅就完成了,很簡單吧。
如果沒有Q.Lee.lulu與烏生魚湯的文章作為參考,對我們來說就不會這么輕松,這也許就是分享的價值吧,你的一點小經驗卻可能給別人帶來很大的幫助。
所以,我們也來分享一下,雖然不算什么經驗,只是一個整理,但也許會對需要的人有幫助。
相關鏈接:sarlmolapple寫了個C#的SDK:http://code.google.com/p/opensinaapi/
原文鏈接:http://www.cnblogs.com/cmt/archive/2010/05/13/1733904.html
【編輯推薦】