c# - 当您尝试阅读 Twitter 帐户的提要时如何修复 (403) 禁止错误
问题描述
我正在尝试在我的网站上显示用户 Twitter 订阅源,但在以下代码中出现 403 错误。
var oAuthConKey = "MYKEY";
var oAuthConSecret="MYSCRET";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "nouman_engineer";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConKey) + ":" +Uri.EscapeDataString((oAuthConSecret)))
));
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();
}
}
但我遇到了错误
第 105 行:WebResponse authResponse = authRequest.GetResponse(); 说“远程服务器返回错误:(403)禁止”
解决方案
我使用的是 TwitterSharp Library 官方版本,它有一些问题,所以我尝试了 TwitterSharp Library 的非官方版本,它解决了这个问题
推荐阅读
- angular - 如何在同一页面中将 id(Parameter ) 从一个地方传递到另一个地方?
- laravel - 如何为 laravel 脚本制作更新或升级选项?
- php - GD 库在服务器中的执行方式不同
- machine-learning - 逻辑回归中连续变量的缩放
- freebsd - 在 FreeBSD 11.2 中找不到 clang 格式
- java - Cloud Firestore - 如何从两个集合中获取关系数据?
- .net - 如何为 ASPNET.Core 应用程序设置 JsonSerializerSettings?
- ms-access - MS Access 表命名宏 - 找不到标识符?
- excel - 如何轻松地将表格从 Excel 更改为 Markdown
- ios - 在 UILabel 中设置文本(带有表情符号、特殊字符、链接),并且链接应该是可点击的