I rejoiced when I finally got some ASP.NET code talking to Twitter's API, and it performed perfectly when testing, creating tweets of any length on my account, mentioning @usernames, and even tweeting 10 times a minute to the same account.
But now I am getting HTTP status code 401 and this JSON back:
{"errors":[{"code":32, "message":"Could not authenticate you."}]}
The errors almost appeared random, until I noticed something. It seems I never used punctuation in any of my previous tests! Now, tweets with apostrophes, brackets and exclamation marks are rejected - yet commas, hyphens and question marks are fine.
The first line of this section must be my problem area:
Dim postBody = "media_ids=" & TwitterMediaID & "&status=" & Uri.EscapeDataString(TextOfTheTweet)
System.Net.ServicePointManager.Expect100Continue = False
Dim request As System.Net.HttpWebRequest = System.Net.WebRequest.Create(TwitterStatusPostURL)
request.Headers.Add("Authorization", OAuthSignature)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
I guess Uri.EscapeDataString()
is the wrong choice of encoding, though I am very grateful to the original author for this code because I would be nowhere without them!
This function takes in Apotrophe' exclamation! brackets() question? fullstop. comma, colon: semicolon; hyphen-
and returns Apotrophe'%20exclamation!%20brackets()%20question%3F%20fullstop.%20comma%2C%20colon%3A%20semicolon%3B%20hyphen-
which is clearly not what Twitter wants to see (or rather, this is something to do with OAuth?).
According to the wonderful table in this SO question there is nothing that encodes an exclamation mark?!
I should be able to find a better function to use, by myself, but I'd love to hear exactly what the problem was here, and have reassurance that I understand which encoding functions are right for which job. This also needs to be documented for future punctuation-addled programmers.
So the question can be summarised as: Why is this function not the right choice, and what should we use? Thanks.