新浪微博的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请求罢了。非常简单。

相关文章:

  • 2022-01-13
  • 2022-12-23
  • 2021-11-25
  • 2022-03-07
  • 2021-06-11
  • 2022-03-03
  • 2021-09-01
  • 2021-05-05
猜你喜欢
  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案