Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Twitter API v1.1 with OAuth

4.89/5 (39 votes)
2 Apr 2015CPOL3 min read 143.2K   17  
Twitter API v1.1 with OAuth.

Introduction   

The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers. More generally, OAuth creates a freely-implementable and generic methodology for API authentication. 

OAuth aims to unify the experience and implementation of delegated web service authentication into a single, community-driven protocol. OAuth builds on existing protocols and best practices that have been independently implemented by various websites. An open standard, supported by large and small providers alike, promotes a consistent and trusted experience for both application developers and the users of those applications.

Recently twitter announced API v1.1 and also deprecated v1.0 API support.

In v1.1 twitter is very strict in terms of authentication. We need to create an application for accessing the Twitters API. 

OAuth_Authentication_Flow_v1.0

Application creation  

For creating an application we need to login with our twitters credentials on https://dev.twitter.com/.

After successfully logged-in click on "Create a new application" to create an application.

Image 2

After that fill the below shown form to create an application.

Provide Application name,description,website URL and call-back URL.
Image 3

 

Image 4

Accept the twitter mentioned rule and regulation and click on "Create your Twitter application" to proceed further and we will see the below screen.

Image 5

Now we have our Consumer Key and Consumer Secret  but we don't have any kind of Access Token and Access Token Secret.

So for generating/creating the access token and access token secret click on "Create Access Token" as shown in below image

Image 6

We will see below screen with the confirmation

Image 7

Cheers guys we have successfully created an application for Twitter.

Now its time to write some code for accessing Twitter API.

Using the code 

Twitter provides many API if we want we can check here.

We will look into code now.

C#
public void Verify_Credentials()
{
    string oauthconsumerkey = "your consumerkey";
    string oauthconsumersecret = "your consumer secret key";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthtoken = "your oauth token";
    string oauthtokensecret = "your oauth token secret";
    string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    string oauthtimestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", "1.0");
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", "HMAC-SHA1");
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_token", oauthtoken);
    //GS - Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/account/verify_credentials.json") + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Since the baseString is urlEncoded we have to remove the last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    //authorization header
    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(
      @"https://api.twitter.com/1.1/account/verify_credentials.json");
    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    hwr.Headers.Add("Authorization", authorizationHeaderParams);
    hwr.Method = "GET";
    hwr.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    hwr.Timeout = 3 * 60 * 1000;
    try
    {
        hwr.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse rsp = hwr.GetResponse() as HttpWebResponse;
        Stream dataStream = rsp.GetResponseStream();
        //Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        //Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
       
    }
}

We can have a look at the description of this API over here

C#
public void Search()
{
    string url = "https://api.twitter.com/1.1/search/tweets.json?q=your search query";
    string oauthconsumerkey = "your consumer key";
    string oauthtoken = "your oauth token";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = "your oauth token secret";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthnonce = Convert.ToBase64String(
      new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("q", "your search query");
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_token", oauthtoken);
    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(
      hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    //authorization header
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);
    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "GET";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        //Proxy settings
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}

We can have a look at the description of this API over here.

C#
public void SendReply()
{
    //If you want to reply to particular tweet then use @screenname along
    //with the status you need to update and status id of that particular
    //tweet to which you want to reply.
    //If you want to update status only then just post the message.
    string status = "@screenname Good day";
    string postBody = "status=" + Uri.EscapeDataString(status);
    string oauth_consumer_key = "your consumerkey";
    string oauth_consumerSecret = "your consumer secret";
    string oauth_signature_method = "HMAC-SHA1";
    string oauth_version = "1.0";
    string oauth_token = "your aouth token";
    string oauth_token_secret = "your oauth token secret";
    string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    //include the "in_reply_to_status_id" parameter if you need to reply to particular tweet.
    basestringParameters.Add("in_reply_to_status_id", 
      "status id of the post to which we are going to reply");
    basestringParameters.Add("status", Uri.EscapeDataString(status));
    basestringParameters.Add("oauth_version", oauth_version);
    basestringParameters.Add("oauth_consumer_key", oauth_consumer_key);
    basestringParameters.Add("oauth_nonce", oauth_nonce);
    basestringParameters.Add("oauth_signature_method", oauth_signature_method);
    basestringParameters.Add("oauth_timestamp", oauth_timestamp);
    if (!string.IsNullOrEmpty(oauth_token))
        basestringParameters.Add("oauth_token", oauth_token);

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("POST" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/update.json") + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //GS - Remove the trailing ambersand char, remember 
    //it's been urlEncoded so you have to remove the 
    //last 3 chars - %26
    string finalBaseString= baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key    
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauth_consumerSecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauth_token_secret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(
      @"https://api.twitter.com/1.1/statuses/update.json?in_reply_to_status_id=status id");

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",";)
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");
    if (!string.IsNullOrEmpty(oauth_token))
      authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    Stream stream = webRequest.GetRequestStream();
    byte[] bodyBytes = new ASCIIEncoding().GetBytes(postBody);
    stream.Write(bodyBytes, 0, bodyBytes.Length);
    stream.Flush();
    stream.Close();

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {

    }
}

We can have a look at the description of this API over here.

C#
public void RequestToken()
{
    string oauthcallback = "your callback URL";
    string oauthconsumerkey = "your consumer key";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = string.Empty;
    string oauthtoken = string.Empty;
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);
    basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("POST" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = Convert.ToBase64String(
      hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;

    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}

We can have a look at the description of this API over here.

C#
public void Authorize()
{
    string oauthconsumerkey = "your consumer key";
    string oauthconsumersecret = "your consumer secret";
    string oauthtokensecret = 
      "Use the oauth_token_secret you receieved as the result of Request_Token API";
    string oauthsignaturemethod = "HMAC-SHA1";
    string oauthversion = "1.0";
    string oauthtoken = "Use the oauth_token you receieved as the result of Request_Token API";
    string url = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauthtoken;
    string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
    TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
    SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
    basestringParameters.Add("oauth_version", oauthversion);
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
    basestringParameters.Add("oauth_nonce", oauthnonce);
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
    basestringParameters.Add("oauth_timestamp", oauthtimestamp);

    //Build the signature string
    StringBuilder baseString = new StringBuilder();
    baseString.Append("GET" + "&");
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split('?')[0]) + "&"));
    foreach (KeyValuePair<string, string> entry in basestringParameters)
    {
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
    }

    //Remove the trailing ambersand char last 3 chars - %26
    string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

    //Build the signing key
    string signingKey = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" +
    EncodeCharacters(Uri.EscapeDataString(oauthtokensecret));

    //Sign the request
    HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
    string oauthsignature = 
      Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));


    //Tell Twitter we don't do the 100 continue thing
    ServicePointManager.Expect100Continue = false;

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

    StringBuilder authorizationHeaderParams = new StringBuilder();
    authorizationHeaderParams.Append("OAuth ");
    authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
    authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
    authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
    authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
    authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
    if (!string.IsNullOrEmpty(oauthtoken))
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\",");
    authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
    webRequest.Headers.Add("Authorization", authorizationHeaderParams);

    webRequest.Method = "GET";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    //Allow us a reasonable timeout in case Twitter's busy
    webRequest.Timeout = 3 * 60 * 1000;
    try
    {
        webRequest.Proxy = new WebProxy("enter proxy details/address");
        HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
        Stream dataStream = webResponse.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    }
    catch (Exception ex)
    {
    }
}
C#
private string EncodeCharacters(string data)
{
    //as per OAuth Core 1.0 Characters in the unreserved character set MUST NOT be encoded
    //unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
    if (data.Contains("!"))
        data = data.Replace("!", "%21");
    if (data.Contains("'"))
        data = data.Replace("'", "%27");
    if (data.Contains("("))
        data = data.Replace("(", "%28");
    if (data.Contains(")"))
        data = data.Replace(")", "%29");
    if (data.Contains("*"))
        data = data.Replace("*", "%2A");
    if(data.Contains(","))
        data = data.Replace(",", "%2C");

    return data;
}                                                
  1. Verify_Credentials API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/account/verify_credentials
  2. Search API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/get/search/tweets
  3. Statuses/Update API: We can have a look at the description of this API over https://dev.twitter.com/rest/reference/post/statuses/update
  4. Request_Token API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/post/oauth/request_token
  5. Authorize API: We can have a look at the description of this API over https://dev.twitter.com/oauth/reference/get/oauth/authorize

Useful Trick

Check the oauth tool for the basestring.It gives us the option to check whether code generated basestring and tool generated basestring are same or not. If it is same then good to go but if code generated basestring is different from tool's basestring then we need to look at our code to make it equal.

As per OAuth Core 1.0, Characters in the unreserved character set MUST NOT be encoded and rest of the characters must be encoded.
unreserved = ALPHA, DIGIT, '-', '.', '_', '~'

Image 8

References

I am not smart enough to write this article on my own. So here is the list of references: 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)