【问题标题】:Update Twitter Status in C#在 C# 中更新 Twitter 状态
【发布时间】:2014-10-19 22:42:11
【问题描述】:

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

我在网上搜索并发现了几种可能性,但我对 Twitter 身份验证过程最近(?)的变化感到有些困惑。我还发现了一个似乎是relevant StackOverflow post 的东西,但它根本无法回答我的问题,因为它是对不起作用的代码 sn-p 进行超特定的重新编码。

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

我研究了两种解决方案。 Twitterizer Framework 工作正常,但它是一个外部 DLL,我宁愿使用源代码。举个例子,使用它的代码非常清晰,看起来像这样:

Twitter twitter = new Twitter("username", "password");
twitter.Status.Update("Hello World!");

我还检查了Yedda's Twitter library,但是在尝试与上述基本相同的代码时,我认为是身份验证过程失败了(Yedda 期望状态更新本身包含用户名和密码,但其他一切都应该一样)。

由于我在网上找不到明确的答案,所以我将它带到 StackOverflow。

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

谢谢

【问题讨论】:

    标签: c# twitter


    【解决方案1】:

    如果您喜欢 Twitterizer 框架但又不喜欢没有源代码,为什么不download the source? (或者browse it,如果你只是想看看它在做什么......)

    【讨论】:

    • 好吧,我想一个愚蠢的问题应该得到一个简单的答案......不知何故,我错过了他们的来源可用的事实。谢谢:)
    【解决方案2】:

    我不喜欢重新发明轮子,尤其是当涉及到已经存在的产品时,它们可以提供 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 */}
    }
    

    【讨论】:

    • 只有 10 行 C# 代码就足以完成 Twitter 的开发框架了! +1
    • @NathanE:有很多东西只有大约 10 行代码,但在库中拥有它们是很好的。它可以防止你犯愚蠢的错误,比如忘记 using 流的语句,以及吞下异常,例如......
    • @NathanE:我仍然坚持 Jon 的建议,即尽可能使用图书馆并在需要时创建图书馆...
    • 嗨,我非常喜欢这段代码并尝试了它,但是如果用户名/密码不正确,它会优雅地失败并且我无法判断操作是否失败(没有抛出异常,我'已将代码放在 catch 子句中)。有什么建议吗?
    • 我会在几个小时后尝试查看。我提供了代码来源的链接。我会去那里看看是否有其他人在 cmets 区域遇到过同样的问题。
    【解决方案3】:

    我成功使用的另一个 Twitter 库是 TweetSharp,它提供了流畅的 API。

    源代码位于Google code。为什么不想使用 dll?这是迄今为止在项目中包含库的最简单方法。

    【讨论】:

      【解决方案4】:

      在 twitter 上发布内容的最简单方法是使用 basic authentication ,这不是很强大。

          static void PostTweet(string username, string password, string tweet)
          {
               // Create a webclient with the twitter account credentials, which will be used to set the HTTP header for basic authentication
               WebClient client = new WebClient { Credentials = new NetworkCredential { UserName = username, Password = password } };
      
               // Don't wait to receive a 100 Continue HTTP response from the server before sending out the message body
               ServicePointManager.Expect100Continue = false;
      
               // Construct the message body
               byte[] messageBody = Encoding.ASCII.GetBytes("status=" + tweet);
      
               // Send the HTTP headers and message body (a.k.a. Post the data)
               client.UploadData("http://twitter.com/statuses/update.xml", messageBody);
          }
      

      【讨论】:

        【解决方案5】:

        试试LINQ To Twitter。使用与 Twitter REST API V1.1 配合使用的媒体完整代码示例查找 LINQ To Twitter 更新状态。解决方案也可供下载。

        LINQ To Twitter 代码示例

        var twitterCtx = new TwitterContext(auth);
        string status = "Testing TweetWithMedia #Linq2Twitter " +
        DateTime.Now.ToString(CultureInfo.InvariantCulture);
        const bool PossiblySensitive = false;
        const decimal Latitude = StatusExtensions.NoCoordinate; 
        const decimal Longitude = StatusExtensions.NoCoordinate; 
        const bool DisplayCoordinates = false;
        
        string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");
        
        var mediaItems =
               new List<media>
               {
                   new Media
                   {
                       Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
                       FileName = "test.jpg",
                       ContentType = MediaContentType.Jpeg
                   }
               };
        
         Status tweet = twitterCtx.TweetWithMedia(
            status, PossiblySensitive, Latitude, Longitude,
            null, DisplayCoordinates, mediaItems, null);
        

        【讨论】:

          【解决方案6】:

          试试TweetSharp。查找 TweetSharp update status with media complete code example 与 Twitter REST API V1.1 一起使用。解决方案也可供下载。

          TweetSharp 代码示例

          //if you want status update only uncomment the below line of code instead
                  //var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
                  Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
                  if (img != null)
                  {
                      MemoryStream ms = new MemoryStream();
                      img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                      ms.Seek(0, SeekOrigin.Begin);
                      Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
                      //Twitter compares status contents and rejects dublicated status messages. 
                      //Therefore in order to create a unique message dynamically, a generic guid has been used
          
                      var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
                      if (result != null && result.Id > 0)
                      {
                          Response.Redirect("https://twitter.com");
                      }
                      else
                      {
                          Response.Write("fails to update status");
                      }
                  }
          

          【讨论】:

            【解决方案7】:

            这是另一个使用出色的 AsyncOAuth Nuget 包和 Microsoft 的 HttpClient 的代码最少的解决方案。此解决方案还假设您代表自己发布,因此您已经拥有访问令牌密钥/秘密,但是即使您不这样做,流程也很容易(请参阅 AsyncOauth 文档)。

            using System.Threading.Tasks;
            using AsyncOAuth;
            using System.Net.Http;
            using System.Security.Cryptography;
            
            public class TwitterClient
            {
                private readonly HttpClient _httpClient;
            
                public TwitterClient()
                {
                    // See AsyncOAuth docs (differs for WinRT)
                    OAuthUtility.ComputeHash = (key, buffer) =>
                    {
                        using (var hmac = new HMACSHA1(key))
                        {
                            return hmac.ComputeHash(buffer);
                        }
                    };
            
                    // Best to store secrets outside app (Azure Portal/etc.)
                    _httpClient = OAuthUtility.CreateOAuthClient(
                        AppSettings.TwitterAppId, AppSettings.TwitterAppSecret,
                        new AccessToken(AppSettings.TwitterAccessTokenKey, AppSettings.TwitterAccessTokenSecret));
                }
            
                public async Task UpdateStatus(string status)
                {
                    try
                    {
                        var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                        {
                            {"status", status}
                        });
            
                        var response = await _httpClient.PostAsync("https://api.twitter.com/1.1/statuses/update.json", content);
            
                        if (response.IsSuccessStatusCode)
                        {
                            // OK
                        }
                        else
                        {
                            // Not OK
                        }
            
                    }
                    catch (Exception ex)
                    {
                        // Log ex
                    }
                }
            }
            

            由于 HttpClient 的性质,这适用于所有平台。我自己在 Windows Phone 7/8 上使用这种方法来提供完全不同的服务。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-03-13
              • 2016-03-12
              • 2012-01-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-04-09
              相关资源
              最近更新 更多