我正在尝试更新用户的状况自我的C#应用程序。

我搜索的网络和发现了几种可能性,但我有点困惑通过最近的(?) 改变在Twitter的身份验证过程。我还找到了什么似乎是一个 有关计算器后, 但它只是不回答我的问题,因为它是超具体regading代码段不起作用。

我试图达到其余API和不搜索API,这意味着我应该达到的严格保护身份验证的认证。

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

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

我也检查了 Yedda的图书馆, 但这一失败什么我认为是身份验证过程,在尝试基本上相同的代码如上述(Yedda预计的用户名和密码的最新情况本身,而是其他的一切都应该是相同)。

因为我不能找到一个明确的答案在网上,我带它来计算器.

什么是最简单的方式得到Twitter状态的更新工作在C#应用程序,没有外部DLL依赖关系?

感谢

有帮助吗?

解决方案

如果你喜欢的Twitterizer框架,但只是不喜欢不具有源,为什么不 下载源?(或 浏览这 如果你只是想看看它在做什么...)

其他提示

我不是一个风扇的重新发明轮子,特别是当它涉及到产品已经存在,提供100%的所寻求的功能。我实际上有源代码 Twitterizer 运行边我的ASP.NET 软应用程序只是让我可以做任何必要的改变...

如果你真的不想DLL参存在,这里就是一个例子如何码更新。看看这个从 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 */}
}

另一个Twitter图书馆我已使用成功是 TweetSharp, ,它提供了一个流利。

源代码可以在 谷歌的代码.为什么你不想使用dll?这是迄今为止最简单的方法包括图书馆的一个项目。

最简单的方法后的东西到twitter是使用 基本的认证 ,这不是很强。

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

尝试 皇宫叽叽喳喳.找到 皇宫叽叽喳喳 更新状况与媒体完全代码的例子,适用的Twitter其余API V1。1.解决方案也是可供下载。

皇宫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);

尝试 TweetSharp .找到 TweetSharp更新状况与媒体完全代码的例子 工作与Twitter其余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");
            }
        }

这里是另一种解决方案与最小的代码使用优秀 AsyncOAuth Nuget和微软的 HttpClient.这种解决也是假设你们张贴在自己的代表这样,你有你的访问令牌键的秘密了,但是即使你不流动是很容易(见AsyncOauth docs).

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

这适用于所有的平台,由于异常的性质。我用这个方法我自己在Windows电话7/8为一个完全不同的服务。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top