用Basic Authentication方式发送新浪微博
时间:2011-01-06 来源:dragonpig
新浪仍然支持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请求罢了。非常简单。
相关阅读 更多 +