文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>用Basic Authentication方式发送新浪微博

用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请求罢了。非常简单。
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载