2009-07-30 105 views
5

我试图从我的C#应用​​程序更新用户的Twitter状态。更新C#中的Twitter状态#

我搜索了网页,发现了几种可能性,但我对Twitter的身份验证过程中最近的(?)更改有点困惑。我也发现了什么似乎是relevant StackOverflow post,但它根本不回答我的问题,因为它是超特定的重新编写了一个无效的代码片段。

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

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

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

我还检查了Yedda's Twitter library,但我认为是认证过程中,试图基本相同的代码时,这一次失败(Yedda预计在状态更新本身的用户名和密码,但其他一切应该是相同的)。

因为我无法在网上找到明确的答案,我将它带到StackOverflow。

获取在C#应用程序中工作的Twitter状态更新,而无需外部DLL依赖关系的最简单方法是什么?

感谢

回答

10

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

+0

嗯,我想一个愚蠢的问题值得一个简单的答案......不知何故,我错过了他们的来源可用的事实。谢谢:) – 2009-07-30 18:00:56

7

我不是重新发明车轮的粉丝,特别是当涉及到已经存在的产品,提供100%的搜索功能。我实际上有Twitterizer源代码并行运行我的ASP.NET MVC应用程序,以便我可以做出任何必要的更改...

如果您确实不希望DLL引用存在,则此处为有关如何在C#中编写更新的示例。从dreamincode检查这一点。

/* 
* A function to post an update to Twitter programmatically 
* Author: Danny Battison 
* Contact: [email protected] 
*/ 

/// <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 */} 
} 
+1

当只有10行C#足以做到这一点时,有很多令人惊讶的发现Twitter的开发框架! +1 – nbevans 2009-07-30 18:28:58

3

我已经成功使用的另一种微库是TweetSharp,它提供一个流畅API。

源代码可在Google code。你为什么不想使用DLL?这是将图书馆纳入项目的最简单方法。

1

向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); 
    } 
0

尝试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"); 
      } 
     } 
1

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

LINQ到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); 
0

下面是用最少的代码出色AsyncOAuth NuGet包和微软的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上使用这种方法来完成一项完全不同的服务。