我已经搜索了几天,无论是高还是低,都无法将 POST 发送到 twitter API 以正常工作。我能够成功获取请求令牌并将其交换为访问令牌,但是当我对状态/更新进行 POST 时,我收到 401 错误。
我已验证标头的授权部分与我在使用 Twitter OAuth 工具时收到的内容完全匹配。
我相信我的问题是我将状态添加到 Web 请求正文的方式。url 是否需要只是https://api.twitter.com/1/statuses/update.json,还是应该是https://api.twitter.com/1/statuses/update.json?status=MyTweetHere ?
我的代码如下:
public string UpdateStatus(string requestMethod, string baseUrl, string consumerKey, string consumerSecret, string accessToken, OAuthRequestType requestType, string status)
{
//baseUrl = https://api.twitter.com/1/statuses/update.json
const string signatureMethod = "HMAC-SHA1";
const string oauthVersion = "1.0";
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
var timestamp = (int)timeSpan.TotalSeconds;
var nonce = CreateNOnce(timestamp, consumerKey, baseUrl, accessToken);
var signature = CreateSignature(requestMethod, baseUrl, consumerKey, consumerSecret, nonce, signatureMethod, timestamp, accessToken, oauthVersion, string.Empty, string.Empty, requestType, status);
var bodyData = "status=" + UrlEncode(status);
var webRequest = (HttpWebRequest)WebRequest.Create(baseUrl);
webRequest.KeepAlive = true;
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Method = requestMethod; //Send in as POST
webRequest.Accept = "*/*";
webRequest.UserAgent = "Renicorp.Social";
webRequest.Headers["Authorization"] = "OAuth " + UrlEncode("oauth_consumer_key") + "=\"" + UrlEncode(consumerKey) + "\", " +
UrlEncode("oauth_nonce") + "=\"" + UrlEncode(nonce) + "\", " +
UrlEncode("oauth_signature") + "=\"" + UrlEncode(signature) + "\", " +
UrlEncode("oauth_signature_method") + "=\"" + UrlEncode(signatureMethod) + "\", " +
UrlEncode("oauth_timestamp") + "=\"" + UrlEncode(timestamp.ToString()) + "\", " +
UrlEncode("oauth_token") + "=\"" + UrlEncode(accessToken) + "\", " +
UrlEncode("oauth_version") + "=\"" + UrlEncode(oauthVersion) + "\"";
string postData = bodyData;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
//Make the web call and return the response
WebResponse response = webRequest.GetResponse();
var responseBody = string.Empty;
Stream stream = response.GetResponseStream();
if (stream != null) responseBody = new StreamReader(stream).ReadToEnd();
return responseBody;
}
更新: 我现在已经编写了一个方法来为 account/verify_credentials.json 执行 GET,并且如果我使用我的应用程序帐户密钥,我能够验证帐户凭据,但是当我尝试使用单独的帐户并提供访问令牌时,我得到了401。