我正在尝试使用使用 OAuth 身份验证的新 Twitter REST API(版本 1.1)执行搜索查询。
我遵循了在以下链接中找到的代码,但将其修改为 GET 请求而不是 POST。 http://www.codeproject.com/Articles/247336/Twitter-OAuth-authentication-using-Net
代码在复制后在这里。
由于我在本地开发,因此我还遵循以下链接的第一个答案中的步骤: Twitter oAuth callbackUrl - localhost development
因此,我在 Twitter 中创建了第二个应用程序,并使用“127.0.0.1”作为回调 URL(同时我将网站地址设置留给了我的生产应用程序)。
尽管如此,我仍然收到 401 未经授权的错误。
有人能理解为什么我无法获得授权吗?
var oauth_token = "MyAccessToken";
var oauth_token_secret = "MyAccessTokenSecret";
var oauth_consumer_key = "MyConsumerKey";
var oauth_consumer_secret = "MyConsumerSecret";
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url = "https://api.twitter.com/1.1/search/tweets.json?q=MyQuery";
var status = "Updating status via REST API if this works";
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(status)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url),
"&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
var postBody = "status=" + Uri.EscapeDataString(status);
ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();