在C#中更新Twitter状态

Roe*_*ler 5 c# twitter

我正在尝试从我的C#应用​​程序更新用户的Twitter状态.

我在网上搜索并发现了几种可能性,但我对Twitter的身份验证过程中最近(?)的变化感到有些困惑.我还发现了似乎是一个相关的StackOverflow帖子,但它根本没有回答我的问题,因为它是超特定的重新登录不起作用的代码片段.

我正在尝试访问REST API而不是搜索API,这意味着我应该实现更严格的OAuth身份验证.

我看了两个解决方案.该Twitterizer框架工作得很好,但它是一个外部DLL,我宁愿使用的源代码.举个例子,使用它的代码非常清晰,看起来像这样:

Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");
Run Code Online (Sandbox Code Playgroud)

我还检查了Yedda的Twitter库,但是当我尝试基本上与上面相同的代码时,这个我认为是认证过程失败了(Yedda期望状态更新本身的用户名和密码,但其他一切应该是相同的).

由于我无法在网上找到明确的答案,我将它带到StackOverflow.

在没有外部DLL依赖的情况下,在C#应用程序中使用Twitter状态更新的最简单方法是什么?

谢谢

Jon*_*eet 10

如果您喜欢Twitterizer Framework但只是不喜欢没有源代码,为什么不下载源代码呢?(或者,如果你只想看看它在做什么,请浏览它 ......)


RSo*_*erg 7

我不是重新发明轮子的粉丝,特别是当它已经存在提供100%所需功能的产品时.我实际上有Twitterizer的源代码并行运行我的ASP.NET MVC应用程序,以便我可以进行任何必要的更改...

如果您确实不希望DLL引用存在,这里有一个关于如何在C#中编写更新的示例.从dreamincode检查出来.

/*
 * A function to post an update to Twitter programmatically
 * Author: Danny Battison
 * Contact: gabehabe@hotmail.com
 */

/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
public static void PostTweet(string username, string password, string tweet)
{
    try {
        // encode the username/password
        string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        // determine what we want to upload as a status
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
        // connect with the update page
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
        // set the method to POST
        request.Method="POST";
        request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
        // set the authorisation levels
        request.Headers.Add("Authorization", "Basic " + user);
        request.ContentType="application/x-www-form-urlencoded";
        // set the length of the content
        request.ContentLength = bytes.Length;

        // set up the stream
        Stream reqStream = request.GetRequestStream();
        // write to the stream
        reqStream.Write(bytes, 0, bytes.Length);
        // close the stream
        reqStream.Close();
    } catch (Exception ex) {/* DO NOTHING */}
}
Run Code Online (Sandbox Code Playgroud)

  • @NathanE:有很多东西只有大约10行代码,但是在库中很好.它可以阻止你制造愚蠢的错误,例如忘记流的"使用"语句,以及吞咽异常,例如...... (5认同)
  • @NathanE:我仍然坚持我的建议,Jon也回应说,尽可能使用图书馆并在需要的时候创建图书馆... (3认同)