我正在尝试使用“GET”请求从我的 c# 应用程序连接到 twitter api。我阅读了以下文章: http: //www.codeproject.com/Articles/247336/Twitter-OAuth-authentication-using-Net 这对我很有效,我能够成功发布推文。但是当我尝试将它与“GET”和 Twitter API 1.1 一起使用时,它一直给我错误“未授权”
这是我的代码:
var oauth_token = "";
var oauth_token_secret = "";
var oauth_consumer_key = "";
var oauth_consumer_secret = "";
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
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();
// message api details
var Id = "111111111111111";// the ID of the tweet need to get info about it
var resource_url = "https://api.twitter.com/1.1/statuses/show.json";
// create oauth signature
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("POST&", 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)));
}
// create the request header
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)
);
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url + "?id=" + Id);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";// "POST";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
StreamReader s = new StreamReader(response.GetResponseStream(), encode);
string test = s.ReadLine();
你能帮助我如何编辑它以使用“GET”吗?
谢谢,