使用Twitter API 1.1 oAuth进行用户身份验证和请求其时间线

47
今天早上我在我的几个网站中收到了可怕的“Twitter REST API v1不再活动。请迁移到API v1.1。”错误信息。
以前,我一直使用JavaScript / JSON调用http://api.twitter.com/1/statuses/user_timeline.json来显示时间轴。
由于这已不再可用,我需要采用新的1.1 API流程。
我需要使用HttpWebRequest对象执行以下操作,而不是使用第三方应用程序:
  1. 使用oauth密钥和密钥进行身份验证
  2. 进行经过身份验证的调用,以拉回并显示用户时间轴

我有传统的和MVC的混合。 - hutchonoid
你看过**这个**吗?Twitter开发网站上也有第三方库列表 - 其中有几个是C#的。 - Jimbo
@Jimbo 你好,谢谢。我需要避免使用第三方库。这是因为我需要在许多不同类型的应用程序(mvc和传统应用程序)、CMS、门户等中使用它。我快要完成了,如果可行的话,我会发布答案。 - hutchonoid
@hutchonoid 在 WebForm 中为所有用户执行关键字搜索是否可能? - Phill Healey
@PhillHealey 是的,我相信你可以。基本上,从 Twitter API 中可用的任何内容都可以公开,尽管您可能需要扩展/修改 GitHub 上的源代码。 - hutchonoid
2个回答

103

以下是我在一个简单的示例中使其工作的步骤。

我需要从Twitter生成oAuth消费者密钥和密钥:

https://dev.twitter.com/apps/new

首先,我对身份验证对象进行反序列化处理,以获取令牌和类型,以便对时间轴调用进行身份验证。

时间轴调用只需读取JSON,因为这是我需要做的全部操作,您可能希望将其自己反序列化为对象。

我在此项目中创建了一个项目:https://github.com/andyhutch77/oAuthTwitterWrapper

更新-我已更新GitHub项目,包括ASP .net Web应用程序和MVC应用程序演示以及NuGet安装。

// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";

// Do the Authenticate
var authHeaderFormat = "Basic {0}";

var authHeader = string.Format(authHeaderFormat,
    Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
    Uri.EscapeDataString((oAuthConsumerSecret)))
));

var postBody = "grant_type=client_credentials";

HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using (Stream stream = authRequest.GetRequestStream())
{
    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
    stream.Write(content, 0, content.Length);
}

authRequest.Headers.Add("Accept-Encoding", "gzip");

WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
    using (var reader = new StreamReader(authResponse.GetResponseStream())) {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objectText = reader.ReadToEnd();
        twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
    }
}

// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
    using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
    {
         timeLineJson = reader.ReadToEnd();
    }
}


public class TwitAuthenticateResponse {
    public string token_type { get; set; }
    public string access_token { get; set; }
}

10
你应该把这个放进一个类里,然后放到Github上供其他人使用 ;) - Jimbo
1
非常感谢您的分享 - 它确实帮助我快速恢复并重新运行!对于您的解决方案,我的建议是允许通过构造函数传递参数到OAuthTwitterWrapper对象,或者通过公开属性传递参数。在我的情况下,我想能够根据页面上可用的房地产数量来改变要显示的推文数量。总之,这是一个不错的解决方案,谢谢! - John Mc
5
太棒了!这篇文章应该被放在 Twitter 文档页面上,这样更容易理解! - timothyclifford
你这位伙计真是帮我省了不少麻烦! - user1017882
我已经尝试了一段时间,参考了几篇其他文章的建议(http://umerpasha.wordpress.com/2013/06/13/c-code-to-get-latest-tweets-using-twitter-api-1-1/),但它们都以不同的方式处理令牌,到目前为止都没有起作用。我可能应该把精力放在调查为什么它们对我不起作用上(似乎对其他人有效),但是当您的替代方案可以一次性完成工作而且没有任何问题时,我不想浪费时间。 - user1017882
显示剩余15条评论

1

创建了一个仅使用JS的解决方案,在不使用新API的情况下获取Twitter帖子并且现在可以指定推文数量:http://goo.gl/JinwJ


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接