2009-07-30 53 views
5

Tôi đang cố gắng cập nhật trạng thái Twitter của người dùng từ ứng dụng C# của tôi.Cập nhật Trạng thái Twitter trong C#

Tôi đã tìm kiếm trên web và tìm thấy một số khả năng, nhưng tôi hơi bối rối bởi sự thay đổi gần đây (?) Trong quá trình xác thực của Twitter. Tôi cũng tìm thấy những gì có vẻ là một relevant StackOverflow post, nhưng nó chỉ đơn giản là không trả lời câu hỏi của tôi bởi vì nó cực kỳ cụ thể regading một đoạn mã mà không hoạt động.

Tôi đang cố gắng truy cập API REST chứ không phải API tìm kiếm, điều đó có nghĩa là tôi nên tuân theo xác thực OAuth chặt chẽ hơn.

Tôi đã xem xét hai giải pháp. Các Twitterizer Framework làm việc tốt, nhưng nó là một DLL bên ngoài và tôi thà sử dụng mã nguồn. Chỉ cần làm ví dụ, mã sử dụng nó là rất rõ ràng và trông giống như vậy:

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

Tôi cũng đã kiểm tra Yedda's Twitter library, nhưng điều này không thành công trên những gì tôi tin là quá trình xác thực, khi cố gắng về cơ bản mã tương tự như ở trên (Yedda dự kiến ​​tên người dùng và mật khẩu trong bản cập nhật trạng thái nhưng mọi thứ khác được cho là giống nhau).

Vì tôi không thể tìm thấy câu trả lời rõ ràng trên web, tôi sẽ đưa nó vào StackOverflow.

Cách đơn giản nhất để cập nhật trạng thái Twitter hoạt động trong ứng dụng C#, không phụ thuộc vào DLL bên ngoài là gì?

Cảm ơn

Trả lời

10

Nếu bạn thích khung Twitterizer nhưng chỉ không thích không có nguồn gốc, tại sao không download the source? (Hoặc browse it nếu bạn chỉ muốn xem nó đang làm gì ...)

+0

Vâng, tôi đoán một câu hỏi ngớ ngẩn xứng đáng với một câu trả lời đơn giản ... Bằng cách nào đó tôi đã bỏ lỡ thực tế nguồn của họ đã có sẵn. Cảm ơn :) –

7

Tôi không phải là người hâm mộ phát minh lại bánh xe, đặc biệt là khi nói đến các sản phẩm đã tồn tại cung cấp 100% chức năng được tìm kiếm . Tôi thực sự có mã nguồn cho Twitterizer chạy bên cạnh ứng dụng ASP.NET MVC của tôi chỉ để tôi có thể thực hiện bất kỳ thay đổi cần thiết nào ...

Nếu bạn thực sự không muốn tham chiếu DLL tồn tại, đây là một ví dụ về cách mã các bản cập nhật trong C#. Kiểm tra điều này từ 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

Thật tuyệt vời khi có các khung phát triển cho Twitter khi chỉ có 10 dòng C# là đủ để làm điều này! +1 – nbevans

+5

@NathanE: Có rất nhiều thứ chỉ có khoảng 10 dòng mã, nhưng rất tốt để có trong thư viện. Nó ngăn cản bạn tạo ra những sai lầm ngớ ngẩn như quên câu lệnh 'using' cho các luồng, và nuốt các ngoại lệ, ví dụ ... –

+3

@NathanE: Tôi vẫn giữ đúng lời khuyên của tôi mà Jon lặp lại cũng sử dụng thư viện ở nơi có thể và tạo ra thư viện nếu bạn cần ... – RSolberg

3

Thư viện Twitter khác mà tôi đã sử dụng thành công là TweetSharp, cung cấp API thông thạo.

Mã nguồn có sẵn tại Google code. Tại sao bạn không muốn sử dụng một dll? Đó là cách dễ nhất để bao gồm một thư viện trong một dự án.

1

Cách đơn giản nhất để đăng nội dung lên Twitter là sử dụng basic authentication, không quá mạnh.

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

Hãy thử TweetSharp. Tìm TweetSharp update status with media complete code example hoạt động với Twitter REST API V1.1. Giải pháp cũng có sẵn để tải xuống.

TweetSharp Mã mẫu

//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

Hãy thử LINQ To Twitter.Tìm trạng thái cập nhật LINQ To Twitter với ví dụ về mã hoàn chỉnh phương tiện hoạt động với API REST của Twitter V1.1. Giải pháp cũng có sẵn để tải xuống.

LINQ Để Twitter Mã mẫu

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

Đây là một giải pháp với mã tối thiểu bằng cách sử dụng tuyệt vời AsyncOAuth NuGet gói và của Microsoft HttpClient. Giải pháp này cũng giả định bạn đang đăng thay mặt cho chính mình vì vậy bạn đã có khóa/mã thông báo truy cập của mình, tuy nhiên ngay cả khi bạn không thực hiện luồng này khá dễ dàng (xem tài liệu 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 
     } 
    } 
} 

Điều này hoạt động trên mọi nền tảng do tính chất của HttpClient. Tôi sử dụng phương pháp này bản thân mình trên Windows Phone 7/8 cho một dịch vụ hoàn toàn khác nhau.

Các vấn đề liên quan