03.10.2010

A Proper UrlEncode Function for oAuth in C#

I needed this for a Twitter app I wrote.  The rub was trying to properly URL-encode all the worlds tweets so that Twitter’s oAuth punt returner wouldn’t drop the football. It was a beating, but I finally got it working:

public string UrlEncodeForOAuth(string value)
{
    value = HttpUtility.UrlEncode(value).Replace("+", "%20");

    // UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F
    value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());

    // these characters are not escaped by UrlEncode() but needed to be escaped
    value = value.Replace("(", "%28").Replace(")", "%29").Replace("$", "%24").Replace("!", "%21").Replace(
        "*", "%2A").Replace("'", "%27");

    // these characters are escaped by UrlEncode() but will fail if unescaped!
    value = value.Replace("%7E", "~");

    return value;
}

Below is my unit test (the oAuth class base code was a gift from @swhitley. Get your copy here).

[TestMethod]
public void FunkyCharTweets()   
{
    oAuthTwitter oAuth = new oAuthTwitter();
    oAuth.ConsumerKey = "K1eHbi3f23VNCiMQUjiQ";
    oAuth.ConsumerSecret = "YroIaXQFYJAIvbF4vBKXTy9vfMUoNGZaufUpNpXns";
    oAuth.Token = "[your twitter test account access token]";
    oAuth.TokenSecret = "[your twitter test account secret token]";

    string tweet = "";
    // pick whichever one you want
    tweet = "Droid Doesn’t — Things I Hate About My Verizon Droid | Shelly Palmer http://linktw.it/9vfyq0";
    tweet = "The common name is Zhōngguó, which is 中國 in traditional Chinese or 中国 in simplified Chinese";
    tweet = "hey ~`!@#$%^&*()-_+=|\\}]{[':;?/>.<, dude http://linktw.it/encode";

    string updateurl = "http://twitter.com/statuses/update.xml";
    string strXmlResp = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, updateurl, "status=" + tweet);
}

I hope this helps a few others out there.  Of course if anyone can improve or simplify the above, I’m all ears.

Like melted butter in your inbox...


Comments are closed

stephen denton photo
  • Subscribe
  • Twitter icon
  • Facebook icon
  • GMail icon