用Basic Authentication方式发送新浪微博

新浪微博的API很大程度上借鉴了Twitter,所以非常容易上手。不过现在有很多访问次数的限制,比如每小时只能发博30条。

新浪仍然支持Twitter已经不再采用的Basic Auth。为了安全性当然应该使用OAuth,但作为示例代码Basic Auth相对容易编程。

public string PostOnSina(string contents)
{
    string username = SINA_USER;
    string password = SINA_PASS;
    string appKey = SINA_APPKEY;
    string url = "http://api.t.sina.com.cn/statuses/update.xml";        
    var request = WebRequest.Create(url) as HttpWebRequest;

    request.Credentials = new NetworkCredential(username, password);
    byte[] authBytes = Encoding.UTF8.GetBytes(username + ":" + password);
    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
    request.Method = "POST";

    request.ContentType = "application/x-www-form-urlencoded";
    var body = "source=" + HttpUtility.UrlEncode(appKey) + "&status=" + HttpUtility.UrlEncode(contents);

    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(body);            
    }

    WebResponse response = request.GetResponse();
    using (Stream receiveStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string result = reader.ReadToEnd();
        return result;
    }
}
其实就是带验证的POST请求罢了。非常简单。

posted @ 2011-01-06 20:59  dragonpig  阅读(1307)  评论(1编辑  收藏  举报