I'm trying to post a Twitter status from my web app, using RestSharp. The following code works perfectly:
var status = "I am fine with posting this status.";
var client = new RestClient("https://api.twitter.com");
// The OAuth keys/tokens/secrets are retrieved elsewhere
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
_consumerKey, _consumerSecret, _accessToken, _accessTokenSecret
);
var request = new RestRequest("/1.1/statuses/update.json", Method.POST);
request.AddParameter("status", status, ParameterType.GetOrPost);
var response = client.Execute(request);
However, this code fails with an authentication error if I include any of the following characters in the status text: ! * ' ( )
Through a lot of forum trawling, I've deduced that this is something to do with the OAuth signature encoding not matching the encoding of the POST parameters. I found this question on SO, but searching the RestSharp issues on GitHub reveals nothing helpful.
I can see some code in the RestSharp source (UrlEncodeRelaxed
) which seems to be manually encoding that particular set of characters to comply with the OAuth encoding specs, so I've tried manually encoding those characters in my status in the same way (with code taken from RestSharp) before passing it in, e.g:
var status = "I'm NOT fine with posting this status.";
string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };
string[] UriRfc3968EscapedHex = new[] { "%21", "%2A", "%27", "%28", "%29" };
for (var i = 0; i < UriRfc3986CharsToEscape.Length; i++)
status = status.Replace(UriRfc3986CharsToEscape[i], UriRfc3968EscapedHex[i]);
But this doesn't work either (I still get the authentication error).
What actually is the problem here, and what should I be doing to correctly encode the status? Or is this a RestSharp bug?