我正在尝试使用Twitter API在Unity3D中按位置搜索推文。 我在创建身份验证签名时遇到问题。当我尝试从Postman发出请求并使用生成的标头时,它也可以在Unity中使用,但是当我尝试自己在Unity中创建签名时,总是会从服务器收到 401未经授权的错误。因此,我确定令牌和机密有效,唯一的问题是签名。 这是我创建签名的方式:
private string CreateSignature(string url)
{
var stringBuilder = new StringBuilder();
stringBuilder.Append("POST&");
stringBuilder.Append(Uri.EscapeDataString(url));
stringBuilder.Append("&");
var dictionary = new SortedDictionary<string, string>
{
{"oauth_consumer_key", _mOauthConsumerKey},
{"oauth_nonce", _mNonce},
{"oauth_signature_method", "HMAC-SHA1"},
{"oauth_timestamp", _mTimeStamp},
{"oauth_token", _mOauthToken},
{"oauth_version", "1.0"}
};
foreach (var keyValuePair in dictionary)
{
stringBuilder.Append(Uri.EscapeDataString(string.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value)));
}
var signatureBaseString = stringBuilder.ToString().Substring(0, stringBuilder.Length - 3);
var signatureKey = Uri.EscapeDataString(_mOauthConsumerSecret) + "&" +
Uri.EscapeDataString(_mOauthTokenSecret);
var hmacsha1 = new HMACSHA1(
ASCIIEncoding.ASCII.GetBytes(signatureKey));
var signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(
ASCIIEncoding.ASCII.GetBytes(signatureBaseString)));
return signatureString;
}
以下是我如何创建随机数和时间戳:
_mNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(
DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));
var timeSpan = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var stamp = ((long)(DateTime.UtcNow - timeSpan).TotalSeconds);
_mTimeStamp = Convert.ToInt64(stamp).ToString(CultureInfo.InvariantCulture);
非常感谢。