使用新浪微博接口发送微博有多种方式,本文介绍使用最简单的Http Basic方法调用新浪的接口。新浪微博开发平台 open.weibo.com,首先需要新建一个应用,得到AppKey就可以了。具体请看代码:
using System; using System.Net; using System.Text; namespace SendWeiboV1 { public class BasicAuth { string username; string password; string key; public string UsernamePassword { get { return username + ":" + password; } } /// <summary> /// 默认构造函数 /// </summary> public BasicAuth() { username = "yourname@xxx.com"; password = "yourpwd"; key = "111222333";//AppKey } public BasicAuth(string username, string password) { this.username = username; this.password = password; this.key = "your app key"; } public BasicAuth(string username, string password, string key) { this.username = username; this.password = password; this.key = key; } /// <summary> /// 发送POST请求,使用普通的Basic方式进行验证 /// 适用于调试,不适用于正式场合 /// </summary> /// <param name="url">请求的weibo接口,post方式</param> /// <param name="Content">请求的内容内容</param> /// <returns>string</returns> public string SendPostRequest(string url, string Content) { string result = string.Empty; //准备调用的URL及需要POST的数据: string data = "source=" + key + "&status=" + Content; //准备用于发起请求的HttpWebRequest对象: WebRequest webRequest = WebRequest.Create(url); HttpWebRequest httpRequest = webRequest as HttpWebRequest; //准备用于用户验证的凭据 CredentialCache myCache = new CredentialCache(); myCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password)); httpRequest.Credentials = myCache; httpRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(UsernamePassword))); //发起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(); //获取服务端的响应内容 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)) { result = reader.ReadToEnd(); } return result; } /// <summary> /// 非Web项目情况下的UrlEncode方法 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string UrlEncode(string str) { StringBuilder sb = new StringBuilder(); byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str) for (int i = 0; i < byStr.Length; i++) { sb.Append(@"%" + Convert.ToString(byStr[i], 16)); } return (sb.ToString()); } } }
效果图: