.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/

posted @ 2010-05-13 07:54  博客园团队  阅读(36079)  评论(57编辑  收藏  举报