问题
I have a simple web page which can create a text-only tweet through the Twitter REST API at https://api.twitter.com/1.1/statuses/update.json sucessfully. I am also able to upload a JPG image to Twitter with https://upload.twitter.com/1.1/media/upload.json and get back a numeric media_id
successfully. What I cannot do is put these two together to create an image tweet: it gets HTTP status code 401 if I add in the media_id!
I am using ASP.NET (I have both VB and C# examples) but I expect the problem is not specific to this language. The only two bits of the tweet code I am changing are where the same 'querystring' is built up:
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}&media_ids={7}";
var baseString = string.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version, Uri.EscapeDataString(TweetText), TwitterMediaID);
and
var postBody = "status=" + Uri.EscapeDataString(TweetText) + "&media_ids=" + TwitterMediaID;
using (System.IO.Stream stream = request.GetRequestStream())
{
byte[] content = System.Text.ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
All this really does is append &media_ids=1104003004334784512
to the end of the string. The rest of my code does not change.
The JSON I am returned is:
{"errors":[{"code":32, "message":"Could not authenticate you."}]}
If I remove &media_ids=12345678901234567
then the code is successful (HTTP status code 200, and lots of useful JSON returned).
I don't believe I need any special permissions to create an image tweet, compared to a text-only tweet. I have read various blogs which mention people had intermittent HTTP 401 errors when using media_ids, which were nothing to do with authentication at all, but none of the solutions they offer applied to my sitation.
The documentation suggests my media_id is good for 2 hours, so how can I be making a mess of the authentication aspect, when my text-only tweets are appearing on my Twitter profile OK?
回答1:
Twitter requires that API requests use OAuth 1.0a authentication. One caveat is that the HMAC-SHA1 signature must be created in a very specific format.
In this case, it requires the baseFormat
to be sorted alphabetically - see https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html
来源:https://stackoverflow.com/questions/55063861/adding-media-ids-to-twitter-api-call-causes-authentication-issue