【问题标题】:Twitter Search API The remote server returned an error: (401) UnauthorizedTwitter Search API 远程服务器返回错误:(401) Unauthorized
【发布时间】:2013-07-03 19:40:25
【问题描述】:

我有一个应用程序尝试对 Twitter 提要进行简单的 GET 调用,但它失败并出现上述错误。在调用下面的代码之前,我能够成功获得 access_token。

string lUrl = "https://api.twitter.com/1.1/search/tweets.json&q=" + HttpUtility.UrlEncode("@typescriptlang");
var headerFormat = "Bearer {0}";
var authHeader = string.Format(
  headerFormat,
  Convert.ToBase64String(Encoding.ASCII.GetBytes(HttpUtility.UrlEncode(access_token)))
);
HttpWebRequest lRequest = HttpWebRequest.CreateHttp(lUrl);
lRequest.Method = "GET";
lRequest.Headers.Add("Authorization", authHeader);
WebResponse lResponse = lRequest.GetResponse();

【问题讨论】:

    标签: c# twitter webclient twitter-oauth


    【解决方案1】:

    好的,这正是您需要做的,我已经对此进行了测试,这是一个可行的解决方案:

            private string oAuthConsumerKey = ConfigurationManager.AppSettings["oAuthConsumerKey"];
            private string oAuthConsumerSecret = ConfigurationManager.AppSettings["oAuthConsumerSecret"];
            private string oAuthUrl = ConfigurationManager.AppSettings["oAuthUrl"];     
            private static string searchFormat = ConfigurationManager.AppSettings["searchFormat"];
            private string searchUrl = string.Format(searchFormat, "%23test");
    
            public string GetSearch()
            {
                // 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
                HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(searchUrl);
                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();
                    }
                }
                return timeLineJson;
            }
    

    您还需要将其添加到 web 或 appsettings 中的 app.config:

    <add key="searchFormat" value="https://api.twitter.com/1.1/search/tweets.json?q={0}"/>
    

    我将在今天晚些时候更新我的 GitHub 项目以包含此内容:

    https://github.com/andyhutch77/oAuthTwitterTimeline

    将有一些代码取消注释以显示搜索。现在我可能不得不重新考虑项目名称,因为它也有搜索功能。

    请注意,如果它不起作用,您可能会遇到 twitter 端的应用程序限制问题。我还读到有些人在共享 IP 地址上有问题。

    【讨论】:

    • 谢谢你,我一定会试一试并告诉你。
    • 谢谢,是的,请告诉我。如果答案不好,我会删除它,以免人们误入歧途。
    • 仍然失败,出现不同的错误,403 Forbidden。抱歉,我不知道如何使用 Git,所以我只是分叉了您的项目并向根目录添加了一个名为 DaveTwitterAttempt.cs 的文件。 link
    • 我在可公开访问的个人资料上使用搜索 API。这有关系吗?
    • 嗨,没问题 re: git,我通常只是使用 'git clone url' 将其复制到本地,这是一个非常方便的命令。好的,以上解决了您的 401 问题,因为第一个呼叫必须是对您进行身份验证。这是第二个不同的呼叫,并且禁止访问。如果你把它留给我,我会在大约 4 小时后为你安排午餐时间,看看我是否能为你找到可行的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2011-09-10
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多