【问题标题】:How can I pull in a user's tweets using the new Twitter API v1.1?如何使用新的 Twitter API v1.1 获取用户的推文?
【发布时间】:2013-10-15 20:41:08
【问题描述】:

所以我目前正在使用它来从用户那里获取一定数量的推文:

public void GetTweets(string username, int tweetCount)
{
    var url = string.Format(
         "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name={0}&count={1}", 
         username, tweetCount);
    XDocument xml = XDocument.Load(url);

    // parse xml
}

使用新的 API 版本,这将不再被允许,我将不得不使用 JSON 发送一个 GET 请求:https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

我迷路的地方是需要使用 OAuth 进行身份验证。我需要一个 Twitter 帐户吗?我四处寻找使用 .NET 执行此操作的示例或教程,但找不到任何东西,只是链接回 v1.1 的 twitter 开发页面

有人可以指导我正确的方向吗?

【问题讨论】:

  • 方向正确吗?关于它的结论?

标签: c# asp.net twitter


【解决方案1】:

您确实需要一个 Twitter 帐户,并且您需要获得一个“消费者密钥”和“消费者秘密”。您可以通过在https://dev.twitter.com/apps 创建一个应用程序来做到这一点。

这是 IHttpHandler 中的一个方法,一旦你有了这些方法,你就可以对其进行调整。它为客户端脚本提供了与https://api.twitter.com/1/statuses/user_timeline.json 端点相同的功能。它在身份验证后请求该数据的 1.1 版本,因此它仅适用于您的应用。

对于比获取推文更复杂的事情,应该使用适当的 OAuth 握手 - 试试 TweetSharp 库:https://github.com/danielcrenna/tweetsharp

下面的代码遵循https://dev.twitter.com/docs/auth/application-only-auth 中描述的过程,但它没有执行此处描述的所有 SSL 检查 - https://dev.twitter.com/docs/security/using-ssl

public void ProcessRequest(HttpContext context)
{
    // get these from somewhere nice and secure...
    var key = ConfigurationManager.AppSettings["twitterConsumerKey"];
    var secret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
    var server = HttpContext.Current.Server;
    var bearerToken = server.UrlEncode(key) + ":" + server.UrlEncode(secret);
    var b64Bearer = Convert.ToBase64String(Encoding.Default.GetBytes(bearerToken));
    using (var wc = new WebClient())
    {
        wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        wc.Headers.Add("Authorization", "Basic " + b64Bearer);
        var tokenPayload = wc.UploadString("https://api.twitter.com/oauth2/token", "grant_type=client_credentials");
        var rgx = new Regex("\"access_token\"\\s*:\\s*\"([^\"]*)\"");
        // you can store this accessToken and just do the next bit if you want
        var accessToken = rgx.Match(tokenPayload).Groups[1].Value;
        wc.Headers.Clear();
        wc.Headers.Add("Authorization", "Bearer " + accessToken);

        const string url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=YourTwitterHandle&count=4";
        // ...or you could pass through the query string and use this handler as if it was the old user_timeline.json
        // but only with YOUR Twitter account

        var tweets = wc.DownloadString(url);
        //do something sensible for caching here:
        context.Response.AppendHeader("Cache-Control", "public, s-maxage=300, max-age=300");
        context.Response.AppendHeader("Last-Modified", DateTime.Now.ToString("r", DateTimeFormatInfo.InvariantInfo));
        context.Response.AppendHeader("Expires", DateTime.Now.AddMinutes(5).ToString("r", DateTimeFormatInfo.InvariantInfo));
        context.Response.ContentType = "text/plain"; 
        context.Response.Write(tweets);
    }
}

你可以:

  • 将获取到的值存储起来供accessToken使用,不需要每次都获取。
  • 通过查询字符串上的参数 - 我认为 user_timeline.json 接受与 v1 版本相同的参数。
  • 根据需要设置与缓存相关的 HTTP 标头 - 必须缓存此响应以避免遇到请求限制。
  • 反序列化服务器上​​的 JSON 并用它做一些不同的事情。但如果你这样做,也许直接使用 TweetSharp。这实际上是为了向客户端脚本提供与以前使用 API v1 相同的 JSON 数据。

【讨论】:

  • 也许然后使用任何库反序列化 List 中的 JSON?有什么推荐的?
【解决方案2】:

我需要一个 Twitter 帐户吗?

Twitter 支持基于用户的身份验证和基于应用程序的身份验证,因此如果您不想使用 Twitter 用户帐户进行身份验证,则不必这样做。完整的细节在这里:

https://dev.twitter.com/docs/auth/application-only-auth

也就是说,我的建议是使用基于用户的身份验证。这是迄今为止最常见的通过 Twitter 进行身份验证的方式,因此更容易找到文档和代码示例。下面是一些例子:

https://dev.twitter.com/docs/auth/oauth/single-user-with-examples

【讨论】:

  • 他们示例页面上的 Twitterizer 对我来说毫无用处。试图调用 TwitterTimeline.HomeTimeline(tokens, options);总是导致 JSONConverter 某处的空引用参数。许多其他人在 stackoverflow 和其他网站上抱怨这个问题。在某处我读到该库从未完全适应使用 1.1 API,而我的经验支持这一点。
猜你喜欢
  • 2014-09-19
  • 2013-08-19
  • 2013-06-09
  • 2013-06-13
  • 2013-06-13
  • 2011-05-08
  • 2016-06-25
  • 2013-12-04
  • 2015-02-21
相关资源
最近更新 更多