我使用非常简单的代码在twitter上发布消息。代码如下:
public void UpdateStatus(string username, string password, string tweetMsg)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweetMsg);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
request.Credentials = new NetworkCredential(username, password);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
string statusUpdate = string.Empty;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
statusUpdate = "status=" + System.Web.HttpUtility.UrlEncode(tweetMsg);
sw.Write(statusUpdate);
}
using (HttpWebResponse resp = (HttpWebResponse) request.GetResponse())
{
// Handle response here
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
catch (WebException ex)
{
Console.WriteLine("Web Error: {0}", ex.Message);
if (ex.Response != null)
{
HttpWebResponse r = (HttpWebResponse)ex.Response;
using (StreamReader esr = new StreamReader(r.GetResponseStream()))
{
Console.WriteLine("Error: {0}", esr.ReadToEnd());
}
}
}
catch (IOException ex)
{
Console.WriteLine("I/O Error: {0}", ex.Message);
}
}
我不确定为什么这段代码不起作用。我得到了例外 远程服务器返回错误:(401)未经授权。 但是,无论我指的是哪个网站,我发现人们都可以使用相同的代码发布消息。
有人可以告诉我这段代码中缺少什么吗?我在此代码中引用的网站是http://www.dreamincode.net/forums/topic/120468-twitter-api-posting-status/
提前致谢....
哈
答案 0 :(得分:0)
Twitter API不再支持基本身份验证进行身份验证。您需要切换到使用令牌而不是密码的OAuth。