2024年1月24日发(作者:)
.NET调用新浪微博开放平台发送微博
1. 首先我们要获取一个App Key,在新浪微博开放平台的“我的应用”中创建一个应用,就会生成App Key,假设是123456。
2. 在新浪微博API文档中找到你想调用的API,这里我们假定调用发表微博的API-statuses/update,url是/statuses/,POST的参数:source=appkey&status=微博内容。其中appkey就是之前获取的App Key。
3. 准备数据
1) 准备用户验证数据:(用来登录并授权)
string username = "t@";
string password = "";
string usernamePassword = username + ":" + password;
username是你的微博登录用户名,password是你的博客密码。
2) 准备调用的URL及需要POST的数据:
string url = "/statuses/";
string news_title = "美丽景色";
int news_id = 62747;
string t_news = ("{0},/n/{1}/", news_title, news_id );
string data = "source=123456&status=" + ode(t_news);
4. 准备用于发起请求的HttpWebRequest对象:
uest webRequest = (url);
bRequest httpRequest = webRequest as bRequest;
5. 准备用于用户验证的凭据:
tialCache myCache = new tialCache();
(new Uri(url), "Basic", new kCredentia
l(username, password));
tials = myCache;
("Authorization", "Basic " +
64String(new ncoding().GetBytes(usernamePassword)));
6. 发起POST请求:
= "POST";
tType = "application/x-www-form-urlencoded";
ng encoding = ;
byte[] bytesToPost = es(data);
tLength = ;
requestStream = uestStream();
(bytesToPost, 0, );
();
上述代码成功执行后,就会把内容发到了你的微博上了。
执行:
1.发送文字微博
代码:
string STATUS;//定义发送的内容
STATUS = ;//获得发送的内容
string status = OrEmpty() ? STATUS : ;//判断发送内容是否为空,是则选择初始值
try
{
(status); //发送消息,调用新浪api,发送微博
= "发送消息"; }
catch (Exception ex)
{
= e;// "发送内容重复了";
}
2.发送带图片微博
代码:
string STATUS;
STATUS = ;//文字信息
string status = OrEmpty() ? "今天真开心?" : STATUS;
string name = me;//获取图片名字?
string fpath = h("upfile") + "" + name;//获取路径
(fpath);
try
{
(status, fpath); //调用新浪api,发送带图片信息
= "发送成功|";
}
catch (Exception ex)
{
= e;// "发送内容重复了";
}
演示:
界面1:
界面2:(登录并授权)
界面3:(发送文字信息)
验证:
界面4:(发送带图片微博)
验证:
其中使用的是网上的SDK,对于一些功能稍微做了改善,加了一个fileupload控件,使得可以选择图片加以发送,相关接口函数简单,发送也比较成功。
总结:
总的来说,新浪api不算简单,如果要去研究具体授权机制的话,这里借用别人的就很快了,如果还需要实现其他的功能,利用新浪官方的api接口函数就可以。

发布评论