我无法正常调用Twitter API。 我必须这样做,因为我使用的软件包出现了问题,并且此修复程序与我的项目不兼容。
我想检索“最近”的推文列表,但我一直收到401。我觉得这是因为我创建签名的方式,但不确定。
我的请求网址是:
https://api.twitter.com/1.1/search/tweets.json?result_type=recent&count=1&q=#hashtag1 OR #hashtag2 OR #hashtag3
我有以下身份验证信息:
Dictionary<string, object> _parameters = new Dictionary<string, object>();
_parameters.Add("oauth_version", "1.0");
_parameters.Add("oauth_nonce", "[VALUE]");
_parameters.Add("oauth_timestamp", [TIMESTAMP]);
_parameters.Add("oauth_signature_method", "HMAC-SHA1");
_parameters.Add("oauth_consumer_key", "[VALUE]");
_parameters.Add("oauth_consumer_secret", "[VALUE]");
_parameters.Add("oauth_token", "[VALUE]");
_parameters.Add("oauth_token_secret", "[VALUE]");
我的“创建签名”方法如下。它使用带有搜索参数的完整URL来构造它:
private static string GenerateSignature(Dictionary<string,object> parameters, Uri requestUri, string consumerSecret, string accessTokenSecret)
{
IEnumerable<KeyValuePair<string, object>> nonSecretParameters;
nonSecretParameters = (from p in parameters
where (!SecretParameters.Contains(p.Key))
select p);
Uri urlForSigning = requestUri;
string signatureBaseString = string.Format(
CultureInfo.InvariantCulture,
"{0}&{1}&{2}",
"GET",
UrlEncode(NormalizeUrl(urlForSigning)),
UrlEncode(nonSecretParameters));
string key = string.Format(
CultureInfo.InvariantCulture,
"{0}&{1}",
UrlEncode(consumerSecret),
UrlEncode(accessTokenSecret));
HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));
return Convert.ToBase64String(signatureBytes);
}
private static string UrlEncode(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
value = Uri.EscapeDataString(value);
value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
value = value
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("$", "%24")
.Replace("!", "%21")
.Replace("*", "%2A")
.Replace("'", "%27");
value = value.Replace("%7E", "~");
return value;
}
private static string NormalizeUrl(Uri url)
{
string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
normalizedUrl += ":" + url.Port;
}
normalizedUrl += url.PathAndQuery + url.Fragment.Replace("%20", " ");
return normalizedUrl;
}
获得签名后,将生成Authorisation
标头,如下所示:
OAuth oauth_consumer_key="[VALUE]",oauth_nonce="[VALUE]",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1565261231",oauth_token="[VALUE]",oauth_version="1.0",oauth_signature="[VALUE]"
然后,我将相关的身份验证参数附加到URL上,并向Twitter API发出请求。最终网址是这样的:
https://api.twitter.com/1.1/search/tweets.json?result_type=recent&count=1&q=%23hashtag1 OR %23hashtag2 OR %23hashtag3